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>
);
}
}
誰かが直接私は、[Facebookのチュートリアル](httpsで働いていたというSETSTATE –
を状態を操作するように見えるです
変数
でのコンポーネントのコンテキストを維持する必要があります。 io/react/docs/forms.html)自体! :D – binarykitten