gpt4 book ai didi

javascript - renderMenuItemChildren 中未定义“this”

转载 作者:行者123 更新时间:2023-11-28 14:53:05 24 4
gpt4 key购买 nike

我正在使用react-bootstrap-typeahead asynchronous searching 。在 renderMenuItemChildren 方法中,我想调用另一个方法 handleSubmit 来获取所选项目的详细信息。

thisrenderMenuItemChildren 内未定义,我无法调用该方法。如有任何帮助,我们将不胜感激。

附注我仍在学习 react ,因此可能存在一个我无法识别的愚蠢错误。

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>
);
}
}

最佳答案

您还需要在构造函数中绑定(bind)函数renderMenuItemChildren:

添加此:

this.renderMenuItemChildren = this.renderMenuItemChildren.bind(this);

这是一篇不错的小博客文章,其中包含多种方法:Blog Post也就是说,我更喜欢 lodash 的 bindAll:

_.bindAll(this, 函数1, 函数2, 函数3)

关于javascript - renderMenuItemChildren 中未定义“this”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43872772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com