一、React当中Class组件内的this指向
所有在类中定义的方法都默认开启局部严格模式,所以在Class组件当中
- 所以指向window对象的this都指向undefined
- 所有内联的的事件处理处理函数当中的this都指向undefined
<script type="text/babel">
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
console.log(1,this) //this指向组件实例
}
handleClick() {
console.log(this) //undefined
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
//React.Component 的子类中有个必须定义的 render() 函数,
//render将会在constructor构造函数之后执行
render() {
console.log(this)
return (
//handleClick在代码中是作为onClick的回调,所以不是通过实例调用的,是直接调用的
//类中的方法默认开启了局部的严格模式,因此handleClick中的this为undefined
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button> -->
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
</script>
二、React当中Class组件this指向undefined的解决方法
-
第一种:通过bind方法改变this的指向
1、在construstor构造函数当中修改:
constructor(props) { super(props); this.state = {isToggleOn: true}; // 为了在回调中使用 `this`,重新绑定为这个Toggle组件实例 this.handleClick = this.handleClick.bind(this); }
2、在内联的jsx语法当中直接使用
render() { console.log(this) return ( <button onClick={this.handleClick.bind(this)}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> --> ); } }
-
第二种:通过箭头函数的方式
1、在定义的地方使用箭头函数
handleClick = () => { this.setState(state => ({ isToggleOn: !state.isToggleOn })); }
2、在jsx事件模板当中使用
render() { return ( //handleClick在代码中是作为onClick的回调,所以不是通过实例调用的,是直接调用的 //类中的方法默认开启了局部的严格模式,因此handleClick中的this为undefined <button onClick={()=>this.handleClick()}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); }
注:js当中严格模式下的this指向参照——Js当中严格模式下,常见的this指向