作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用react-bootstrap-typeahead asynchronous searching 。在 renderMenuItemChildren
方法中,我想调用另一个方法 handleSubmit
来获取所选项目的详细信息。
this
在 renderMenuItemChildren
内未定义,我无法调用该方法。如有任何帮助,我们将不胜感激。
附注我仍在学习 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/
我正在使用react-bootstrap-typeahead asynchronous searching 。在 renderMenuItemChildren 方法中,我想调用另一个方法 handle
我是一名优秀的程序员,十分优秀!