class Content extends Component {
constructor(props) {
super(props);
this.state = {
content: '123',
count: 0
};
this.addCount = this.addCount.bind(this);
}
componentDidMount() {
const _this = this;
setTimeout(() => {
_this.setState({ content: 'change' });
// _this.state.content = 1;
}, 1000);
}
addCount() {
let count = this.state.count;
this.setState({
count: ++count
});
}
render() {
return (
<div>
<div>content:{this.state.content}</div>
<div>count: {this.state.count}</div>
<button onClick={this.addCount}>增加数量</button>
</div>
);
}
}
Tips:
- React中主要通过onXXXX来完成对于特定函数的绑定。
- 触发事件中如果用到了this一定要通过bind进行绑定,不能用apply和call,因为apply和call是立即执行函数。