无状态函数式(stateless)
写法一
const Hello = (props) => (
<div> Hello {props.title} {props.name} </div>
)
写法二
function HelloComponent(props, /* context */) {
return (
<div>Hello {props.name}</div>
)
}
ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode)
ES5 React.createClass
var CommentBox = React.createClass({
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
},
render: function() {
return (
<div className="">
</div>
);
}
});
ES6 React.component
import React, {Component} from 'react'
export class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
//TODO
</div>
);
}
}
注意:
React.component 创建的组件,其成员函数不会自动绑定 this
class Contacts extends Component {
constructor(props) {
super(props);
}
handleClick() {
console.log(this); // null
}
render() {
return (
<div onClick={this.handleClick}></div>
);
}
其绑定 this 通常有3种方法
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this); //构造函数中绑定
}
<div onClick={this.handleClick.bind(this)}></div> //使用bind来绑定
<div onClick={()=>this.handleClick()}></div> //使用arrow function来绑定,自动捕捉其所在上下文
或者在声明时使用箭头函数
handleIncrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = {...counter};
counters[index].value++;
this.setState({counters});
};
<Counters
counters={counters}
onReset={this.handleReset}
onDelete={this.handleDelete}
onIncrement={this.handleIncrement} />
1、只要有可能,尽量使用无状态组件创建形式。否则(如需要state、生命周期方法等),使用`React.Component`这种es6形式创建组件
2. 使用原生事件绑定,在组件销毁时需要手动移除监听