在 Redux 中,我什么时候需要使用 .bind(this)



有时我真的很困惑,什么时候需要将.bind(this)附加到方法(ES5)或使用箭头函数(ES6)例如

    handleSubmit(e) {
        console.log(this)
    }
    handleChange(e) {
        console.log(this)
    }
    render() {
        return (
            <div className="col-sm-4">
                <form onChange={e => this.handleChange(e)} onSubmit={e => this.handleSubmit(e)}>
                    <input type="text" name="user" placeholder="user"/>
                    <input type="text" name="comment" placeholder="comments"/>
                    <input type="submit" hidden/>
                </form>
            </div>
        )
    }

所以如果我想访问 handleChangehandleSubmit 内部的this,那么我必须使用 onChangeonSubmit 的箭头功能,否则onChangeonSubmit可以更改为:

<form onChange={this.handleChange} onSubmit={this.handleSubmit}>

我说的对吗?谢谢

是的,每次将自定义函数传递给事件处理程序(如 onChangeonSubmit 时,都需要.bind

这是由 React.createClass() 与扩展 React.Component 中的this上下文差异引起的。

使用

React.createClass() 将自动正确绑定此上下文(值),但在使用 ES6 类时并非如此。当以 ES6 方式(通过扩展 React.Component)执行此操作时,默认情况下会null此上下文。类的属性不会自动绑定到 React 类(组件)实例。

顺便说一句,.bind并不是唯一可用的选择。请参阅我的回答 这里 总结我所知道的所有方法。

PS:实际上,这不是 Redux 特定的东西 - 与 Redux 的工作方式无关。这是一个纯粹的 ReactJS 相关行为。

是的,你是对的,当然,如果你的意思是this是你的类的上下文。在我看来,在这些情况下使用.bind更清楚,但我不知道这是否更有效。

在您的示例中,您可以箭头函数并按照您所说的方式制作表单。

另一种选择是使用绑定的构造函数。

constructor() {
  super();
  this.handleChange = this.handleChange.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
}

那么你的表格将是 <form onChange={this.handleChange} onSubmit={this.handleSubmit}>

有多种方法可以将函数绑定到正确的上下文。

当您想使用函数或属性时,您是对的 在 React 类的上下文中定义,那么你需要 绑定函数。

绑定函数

的另一种方法是在构造函数中指定绑定

喜欢

constructor(){
  super();
  this.handleSubmit = this.handleSubmit.bind(this);
  this.handleChange = this.handlechange.bind(this);
}

class App extends React.Component {
constructor(){
    super();
    this.state = {
       val: 'abc'
     }
    
}
handleSubmit(e) {
        console.log(this.state.val)
    }
    handleChange(e) {
        console.log(this.state.val)
    }
    render() {
        return (
            <div className="col-sm-4">
                <form onChange={e => this.handleChange(e)} onSubmit={e => this.handleSubmit(e)}>
                    <input type="text" name="user" placeholder="user"/>
                    <input type="text" name="comment" placeholder="comments"/>
                    <input type="submit" hidden/>
                </form>
            </div>
        )
    }
    
    }
    
    ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id="app"></div>

最新更新