我熟悉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
这是在context
的React Component
因此你只绑定(bind)一次而不是两次。
我希望我能够正确解释情况
关于javascript - 构造函数中的 bind(this) 在 ReactJS 中做了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42556083/