javascript - 构造函数中的 bind(this) 在 ReactJS 中做了什么

标签 javascript reactjs

我熟悉Javascript函数绑定(bind)。但我不明白为什么在下面的 React.js 片段中 this 再次绑定(bind)到 this。 has 是构造函数的共同点,因为构造函数中的 this 可以根据使用情况具有不同的值?

预先感谢您的回复

class QuotesLibrary extends React.Component {
  constructor(props) {
    super(props);
    this.search = debounce(this.search.bind(this), 300);
  }
  search(searchTerm) {
    this.props.relay.setVariables({searchTerm});
  }
  render() {
    return (
      <div className="quotes-library">
        <SearchForm searchAction={this.search} />
        <div className="quotes-list">
          {this.props.library.quotesConnection.edges.map(edge =>
            <Quote key={edge.node.id} quote={edge.node} />
          )}
        </div>
      </div>
    )
  }
}

最佳答案

什么this.search.bind(this)它是否绑定(bind)了 key this在函数内部到你的 React 组件的上下文中,它基本上意味着每当你尝试访问 React Component 的属性时,您可以像 this.props 一样访问它自从 this然后将引用 React 组件的上下文而不是函数本身。
this.search的意义|之前 bind是它试图访问函数search这是在contextReact Component因此你只绑定(bind)一次而不是两次。

我希望我能够正确解释情况

关于javascript - 构造函数中的 bind(this) 在 ReactJS 中做了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42556083/

相关文章:

javascript - Uncaught TypeError : $(. ..).code is not a function (Summernote)

reactjs - Cypress session 重定向到空白页

javascript - 类的属性名称是什么?

javascript - ReactJS ES6 函数绑定(bind) - 未捕获的类型错误 : Cannot read property 'update' of undefined

javascript - Django : Ajax form still reloads the whole page

javascript - 如何在javascript中从左到右从字符串序列中选择数字整数

javascript - Highcharts ;禁用单个点的工具提示会呈现一个随机的小框

reactjs - React Routing 导致输入失去焦点

Javascript contenteditable 错误

Javascript SVG 调整大小适用于 Chrome,但不适用于 Safari