前言
我们先来看下面这段代码:
components/MyComponent.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import React from "react";
export default class MyComponent extends React.Component { constructor(props) { super(props);
this.state = { msg: "这是 MyComponent 组件 默认的msg" }; }
render() { return ( <div> <h1>绑定This并传参</h1> <input type="button" value="绑定this并传参" onClick={this.changeMsg} /> <h3>{this.state.msg}</h3> </div> ); }
changeMsg() { console.log(this); this.setState({ msg: "设置 msg 为新的值" }); } }
|
上面的代码中,点击按钮,执行 changeMsg() 方法,尝试修改 this.state.msg 的值。但是,这个方法执行的时候,是会报错的:
1
| Uncaught TypeError: Cannot read property 'setState' of null
|
而且,打印this的结果也是 undefined。这是为啥呢?因为这里的 this 并不是指向 MyComponent 组件本身。
那如何让 changeMsg() 方法里面的 this,指向MyComponent 组件呢?办法总是有的,比如说,将changeMsg() 修改为箭头函数:
1 2 3 4 5 6
| changeMsg = () => { console.log(this); this.setState({ msg: "设置 msg 为新的值" }); };
|
那么,除了箭头函数可以 绑定 this,还有没有其他的