从同一个类中的另一个方法访问一个方法,该方法作为props传递给另一个类

时间:2016-09-14 11:00:11

标签: javascript events reactjs typescript onclick

我的Search.tsx类中有以下方法。

    renderSuggestion(suggestion) {
    <div className="buttons">
        <button className="button">View Location</button>
        <button className="button whitebutton" onClick={this.handleThatEvent.bind(this)}>Add to price checker</button>
    </div>

}

render() {
        <Autosuggest
            suggestions={suggestions}
            onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
            onSuggestionsClearRequested={this.onSuggestionsClearRequested}
            getSuggestionValue={this.getSuggestionValue}
            renderSuggestion={this.renderSuggestion}
            inputProps={inputProps}/>
}

public  handleThatEvent(e){
            //MOUSE CLICK LOGIC HERE
};

此处将renderSuggestion方法传递给AutoSuggest组件。当单击renderSuggestion中的按钮时,我需要调用方法handleThatEvent。但是如何从renderSuggestion方法访问此方法?我尝试在构造函数中将“that”分配给“this”并尝试调用方法that.handleThatEvent。但“那个”返回undefined。如何在renderSuggestion方法的按钮单击事件中调用此handleThatEvent?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

就像绑定handleThatEvent方法一样,您应该绑定renderSuggestion方法:

<Autosuggest
    suggestions={suggestions}
    onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
    onSuggestionsClearRequested={this.onSuggestionsClearRequested}
    getSuggestionValue={this.getSuggestionValue}
    renderSuggestion={this.renderSuggestion.bind(this)}
    inputProps={inputProps}/>

但我建议你不要将html从一个组件插入另一个组件,反应的理念是每个组件都将管理自己的状态。
您应该在renderSuggestion组件中使用Autosuggest方法,并将其传递给处理函数:

<Autosuggest
    suggestions={suggestions}
    onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
    onSuggestionsClearRequested={this.onSuggestionsClearRequested}
    getSuggestionValue={this.getSuggestionValue}
    onSuggestionButtonClick={this.handleThatEvent.bind(this)}
    inputProps={inputProps}/>