我正在使用react-bootstrap-typeahead asynchronous searching。在renderMenuItemChildren
方法中,我想调用另一个方法handleSubmit
来获取所选项目的详细信息。this
在renderMenuItemChildren
内部未定义,我无法调用该方法。任何帮助表示赞赏。
附言我仍在学习反应,因此可能无法识别一个愚蠢的错误。
class App extends Component {
constructor(props) {
super(props);
this.state = {
searchTitle: '',
defaultUrl: 'http://www.omdbapi.com/?t=arrival'
};
this.handleSearch = this.handleSearch.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.fetchApiData = this.fetchApiData.bind(this);
}
componentDidMount() {
this.fetchApiData(this.state.defaultUrl);
}
fetchApiData(url){
fetch(url)
.then((result) => {
return result.json()
})
.then((json) => {
if(json.Response === "True"){
this.setState({
title: json.Title,
year: json.Year,
released: json.Released,
runtime: json.Runtime,
genreList: json.Genre,
actors: json.Actors,
plot: json.Plot,
poster_url: json.Poster,
rating: json.imdbRating,
boxOffice: json.BoxOffice,
votes: json.imdbVotes,
response: json.Response
});
}
else {
this.setState({
response: json.Response,
error: json.Error
});
}
})
.catch((err) => {
console.log(err);
})
}
handleSubmit(query){
if (!query) {
return;
}
this.fetchApiData(`http://www.omdbapi.com/?t=${query}`);
}
handleSearch(query) {
if (!query) {
return;
}
fetch(`http://www.omdbapi.com/?s=${query}`)
.then((result) => {
return result.json()
})
.then((json) => {
//console.log(json.Search);
this.setState({
options: json.Search
})
});
}
renderMenuItemChildren(option, props, index) {
return (
<div key={option.imdbID} onClick={() =>
this.handleSubmit.bind(option.Title)}>
<span>{option.Title}</span>
</div>
);
}
render() {
return (
<div className="row">
<div className="col-xs-12 col-lg-10 col-lg-offset-1">
<div className="App-header col-xs-12">
<div className="row">
<div className="col-xs-12 col-sm-6 col-lg-5">
<h1><a href="http://www.omdbapi.com/" className="omdb-link" title="The Open Movie Database">OMDb</a></h1>
</div>
<div className="col-xs-12 col-sm-6 col-lg-7">
<AsyncTypeahead
ref="typeahead"
{...this.state}
labelKey="Title"
onSearch={this.handleSearch}
options={this.state.options}
placeholder='Search Title'
className="search-input-box"
renderMenuItemChildren={this.renderMenuItemChildren}
/>
</div>
</div>
</div>
<SearchBody data={this.state} />
</div>
</div>
);
}
}
最佳答案
您在这里不需要=>函数。您可以使用以下代码将标题值传递回handleSubmit()
renderMenuItemChildren(option, props, index) {
return (
<div key={option.imdbID} onClick={this.handleSubmit.bind(this, option.Title)}>
<span>{option.Title}</span>
</div>
);
}