React文档源码
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true};
// 为了在回调中使用 `this`,这个绑定是必不可少的
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={
this.handleClick}>
{
this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
为什么要用bind重新绑定?
首先一点,React这是使用的ES6的 class
,它只是一种语法糖(只要它能实现的,ES5也能实现)。
而使用 class 创建的对象,在没有通过 new
关键字去实例化的之前,它的内部方法this是无绑定状态的。
也就是说上面的代码,handleClick
方法如果不做绑定,那么这个方法的 this
会指向 undefined
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true};
// 为了在回调中使用 `this`,这个绑定是必不可少的
// this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this) // 输出是 undefined
}
render() {
return (
<button onClick={
this.handleClick}>
{
this.state.isToggleOn ? 'ON' : 'OFF'}
</button>