1. 在 React 中的事件处理函数中,我们需要使用构造函数中将方法绑定到组件实例上。

js
import React from "react"; export default class Demo extends React.Component { constructor(props) { super(props); this.state = { count: 0, }; this.add = this.add.bind(this); } add() { this.setState({ count: this.state.count + 1 }); } render() { return ( <div> <h2>count: {this.state.count}</h2> <button onClick={this.add}>+1</button> </div> ); } }

为了理解上面的问题,我们首先得理解 Javascriptthis 的工作原理。

2. Javascript 中的 this

【JS基础-作用域和闭包】this 的绑定规则有哪些?优先级?

3. React 中的 this

React 在处理事件时会创建一个新的函数作为事件处理函数,而不是直接使用组件实例中的方法。这个新函数中的 this 关键字默认指向 undefined,而不是组件实例。相当于下面的例子

js
class Foo { constructor(name){ this.name = name this.display = this.display.bind(this); } display(){ console.log(this.name); } } var foo = new Foo('Saurabh'); foo.display(); // Saurabh var display = foo.display; display(); // Saurabh

事实上,我们不一定非要绑定this,通过箭头函数同样可以,如下:

js
import React from "react"; export default class Demo extends React.Component { constructor(props) { super(props); this.state = { count: 0, }; } add = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <h2>count: {this.state.count}</h2> <button onClick={this.add}>+1</button> </div> ); } }
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:叶继伟

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!