出于某种原因,当我尝试将函数绑定到我的React组件中的prop时,它就会出现
TypeError:无法在onSearch上添加属性,对象不可扩展。
我不太熟悉这意味着什么或它出现的原因,我认为这可能与es6绑定有关,我仍然在寻找解决方法。
以下是两个最相关的组件。
搜索框
import React from 'react';
import SearchForm from 'SearchForm';
import searchDisplay from 'searchDisplay';
import googleRequests from 'googleRequests';
class SearchBox extends React.Component {
constructor() {
super();
this.state = {
searchResults: []
}
this.handleSearch = this.handleSearch.bind(this);
}
handleSearch(searchTerm) {
googleRequests.search(searchTerm).then((response) => {
console.log(response.items);
this.extrapolateResults(response.items);
}), ((error) =>{
console.log(error)
});
}
//pull relevant data out of api call
extrapolateResults(arr) {
function Book(objInArr) {
this.link = objInArr.selfLink;
this.bookTitle = objInArr.volumeInfo.title;
this.author = objInArr.volumeInfo.authors;
this.bookDescription = objInArr.volumeInfo.description;
this.thumbnail = function() {
if (objInArr.volumeInfo.hasOwnProperty('imageLinks')){
return objInArr.volumeInfo.imageLinks.smallThumbnail
}
else {
return "No Thumbnail Available";
}
};
this.thumbnailPic = this.thumbnail();
}
//push extrapolated data into array
var finalRes = [];
var initRes = arr;
initRes.forEach(function (objInArr) {
var obj = new Book(objInArr);
finalRes.push(obj);
})
this.setState({
searchResults: finalRes
})
console.log(finalRes, this.state.searchResults)
}
render() {
var res = this.state.searchResults;
function renderResults() {
if (res.length !== 0) {
return (<SearchDisplay content={res} />)
}
else {
return;
}
}
var style = {
border: '1px solid black',
height: '80%',
width: '83%'
}
return (
<div style={style}>
<SearchForm onSearch={this.handleSearch}> </SearchForm>
</div>)
}
};
export default SearchBox;
Searchform
import React from 'react';
class SearchForm extends React.Component {
constructor(props) {
super(props);
this.onFormSubmit = this.onFormSubmit.bind(this);
this.props.onSearch = props;
}
onFormSubmit(e) {
e.preventDefault();
var searchTerm = this.refs.searchTerm.value;
if (searchTerm.length > 0) {
this.refs.searchTerm.value = '';
this.props.onSearch(searchTerm);
}
}
render() {
var style = {
border: '1px solid black',
float: 'left',
height: '100%',
width: '30%'
}
return(
<div style={style} className="container">
<form onSubmit={this.onFormSubmit}>
<input type="text" placeholder="search name here" ref="searchTerm"/>
<input type="submit" className="button" value="Get Book"/>
</form>
</div>
);
}
};
export default SearchForm;
我有一种感觉我错过了一些非常简单的东西但是在谷歌搜索了一段时间之后我仍然无法弄清楚它是什么......
答案 0 :(得分:2)
删除this.props.onSearch = props;
...不确定你想在那条线上做什么
答案 1 :(得分:0)
将handleSearch函数定义更改为handleSearch =()=> {}胖箭头函数 它将在搜索框文件中正常工作。