反应组件中的绑定函数

bind function in react component

本文关键字:绑定 函数 组件      更新时间:2023-09-26

我在 React 中创建了一个组件,并且在其中使用了某个函数例如

class A {
   changeDid(e) {
  }
   render() {
    return (
      <input type="text" onChange{this.changeDid.bind(this)}>
    )
  }
}

我想了解一行 this.changeDid.bind(this)谁能帮我这个??

bind()方法创建一个新函数,该函数在调用时具有其 此关键字设置为提供的值,具有给定的序列 调用新函数时提供的任何参数前面的参数。

this.changeDid.bind(this)的意思是,在changeDid this中会被引用A,所以你可以得到与A相关的方法。

class A {
  changeDid(e) {
     this.someMethod();
  }
  someMethod() {
    // ... 
  }
  render() {
    return (
      <input type="text" onChange={this.changeDid.bind(this)}>
    )
  }
}

但是如果你传递给onChange={ this.changeDid }this将引用全局范围(在浏览器中它是window,或者如果你使用strict mode,则undefined),前面的例子将不起作用,因为someMethod存在于A中,但不存在于window

我为您创建了一个简单的例子。

class Example extends React.Component {
  constructor(){
    this.state = {
      item : 'hello World'
    }
    /* this.click = this.click.bind(this) */
  }
  click(){
     console.log(this)
     console.log(this.state.item)
  }
    render(){
    return <div>
       <button onClick={this.click}>Click Me</button>
    </div>
  }
}
React.render(<Example />, document.getElementById('container'));

因此,如果您单击一个按钮,您将在console中得到下一个:

 console.log(this) // undefined 
 console.log(this.state.item) // Type Error, Cannot read property 'state' of undefined

发生这种情况是因为click方法内部this链接到undefined,但我们想显示我们的states

你怎么能解决它?为了确保我们在方法中获得正确的上下文click我们bind(this)它。/* this.click = this.click.bind(this) */从此行中删除注释,您将获得方法的正确行为。

工作示例小提琴

我希望它能帮助你。

谢谢。