我在React中有一個父組件(BookApplication
)和一個子組件(SearchBox
)。 SearchBox有一個輸入字段,並應該將輸入返回給父級以處理事件。這工作正常,但是當我回到方法handleSearch
中的父組件時,this.state...
未定義。React組件方法this.state.myState在從子組件返回後未定義
TypeError: Cannot read property 'books' of undefined
但searchInput有它應該有的值。 但我需要從this.state.books書籍再次:/ 我明白,在方法handleSearch
我工作在它的範圍內,所以this....
是handleSearch的上下文...但我怎麼得到它的組件的參數BookApplication
呢? 我仍然在學習JavaScript,我認爲這不應該是一個問題,因爲一個函數總是可以使用它的父對象的變量?
class BookApplication extends React.Component {
constructor() {
super();
this.state = {books: []};
}
componentDidMount() {
$.get(PATH, function (result) {
this.setState({
books: result
});
}.bind(this));
}
handleSearch(searchInput) {
//Sort the books list
var sortedList = [];
this.state.books.map(
function (currentBook) {
currentBook.keys().forEach(
function (key, pos) {
if (key.contains(searchInput)) {
sortedList.push(currentBook)
}
}
)
}
);
}
render() {
return (
<div>
<SearchBox onSearch={this.handleSearch}/>
<div className="book-list">
{this.state.books.map(function (currentBook) {
return <Book book={currentBook} key={currentBook.id}/>;
}) }
</div>
</div>
);
}
這裏也是我的搜索盒:
class SearchBox extends React.Component {
constructor(props) {
super(props);
this.state = {searchFieldInput: ''};
this.handleSearchChange = this.handleSearchChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSearchChange(event) {
this.setState({searchFieldInput: event.target.value});
}
handleSubmit(e) {
//Prevent the browser's defeault action of submitting the form
e.preventDefault();
var searchFieldInput = this.state.searchFieldInput.trim();
//Call the passed callback function
this.props.onSearch({searchFieldInput: searchFieldInput});
}
render() {
return (
<div className="book-search">
<input
type="text"
value={this.state.searchFieldInput}
onChange={this.handleSearchChange}
placeholder="Search..."
className="search-bar"
/>
<button onClick={this.handleSubmit} className="search-button">Search</button>
</div>
);
}
}
看起來像有人直接操作狀態,而的setState –
我是用[Facebook的教程](HTTPS工作://facebook.github。 io/react/docs/forms.html)本身! :D – binarykitten