React组件方法中this指向undefined及react-autosuggest事件绑定问题
嘿,这个问题我之前也碰到过!本质上是renderSuggestion方法里的this上下文丢失了,导致没法访问到父组件传递的onClick函数。下面给你几个靠谱的解决办法:
解决react-autosuggest中renderSuggestion的this指向问题
问题核心:类组件中的普通方法默认不会绑定组件实例的this,当react-autosuggest调用你的renderSuggestion时,this就变成了undefined,自然没法访问到组件的props(包括父组件传的onClick)。
方案1:用箭头函数定义renderSuggestion(最简洁)
箭头函数会自动捕获当前上下文的this,直接解决指向问题:
import Autosuggest from 'react-autosuggest' import React from 'react' export class SearchBar extends React.Component { // 用箭头函数定义renderSuggestion renderSuggestion = (suggestion) => { // 这里的this就指向组件实例了,能正常访问this.props.onClick return ( <div onClick={() => this.props.onClick(suggestion)}> {suggestion.name} </div> ) } // 配套的getSuggestionValue也建议用箭头函数 getSuggestionValue = (suggestion) => suggestion.name render() { const { suggestions, value, onChange } = this.props const inputProps = { placeholder: '搜索...', value, onChange } return ( <Autosuggest suggestions={suggestions} onSuggestionsFetchRequested={this.props.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.props.onSuggestionsClearRequested} getSuggestionValue={this.getSuggestionValue} renderSuggestion={this.renderSuggestion} inputProps={inputProps} /> ) } }
方案2:在constructor中手动绑定this
如果习惯用普通函数定义方法,可以在构造函数里手动把this绑定到方法上:
import Autosuggest from 'react-autosuggest' import React from 'react' export class SearchBar extends React.Component { constructor(props) { super(props) // 手动绑定renderSuggestion的this到组件实例 this.renderSuggestion = this.renderSuggestion.bind(this) this.getSuggestionValue = this.getSuggestionValue.bind(this) } renderSuggestion(suggestion) { return ( <div onClick={() => this.props.onClick(suggestion)}> {suggestion.name} </div> ) } getSuggestionValue(suggestion) { return suggestion.name } render() { // ... 省略其余和方案1相同的代码 } }
方案3:传递方法时临时绑定this
这种方式不需要修改方法定义,直接在Autosuggest的props里绑定:
<Autosuggest suggestions={suggestions} onSuggestionsFetchRequested={this.props.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.props.onSuggestionsClearRequested} getSuggestionValue={this.getSuggestionValue.bind(this)} renderSuggestion={this.renderSuggestion.bind(this)} // 在这里绑定this inputProps={inputProps} />
不过要注意:这种方式每次render都会创建新的函数实例,会有微小的性能损耗(大部分场景下可以忽略),所以更推荐前两种方案。
另外提醒下:如果要把suggestion数据传给父组件的onClick,记得用箭头函数包裹或者绑定参数,别直接写onClick={this.props.onClick}——那样会把点击事件对象传进去,而不是你要的suggestion内容。
内容的提问来源于stack exchange,提问作者user5948213
相关产品推荐
相关产品推荐

