在我的 app.js 中,我有这个
render() {
return (
<div id="App">
<SearchBar />
</div>
);
}
在SearchBar内部,我导入react-autosuggest并得到这个-
render() {
const { value, suggestions } = this.state;
const inputProps = {
placeholder: "Search",
value,
onChange: this.onChange
};
return (
<Autosuggest
style={style}
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
onSubmit={this.doSomething}
/>
);
}
所有这些函数都是react-autosuggest使用的标准样板函数。如何访问在其父级 app.js 内的 SearchBar 内搜索的内容?
最佳答案
您可以使用 props 将 Autosuggest
事件中的数据提升到父组件。在 App
内创建一个方法,并将其作为 prop 传递给 SearchBar
组件。然后,使用 Autosuggest
事件调用它。
应用程序
class App extends React.Component {
onSubmit(e) {
// `e` is the data that was passed through from the `Autosuggest` event.
console.log(e);
}
render() {
return (
<div id="App">
<SearchBar onSubmit={this.onSubmit} />
</div>
);
}
}
搜索栏
<Autosuggest onClick={this.props.onSubmit} />
关于reactjs - 如何将react-autosuggest内部的值传递给父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46165097/