我在React中有一个Parent组件(BookApplication
)和一个子组件(SearchBox
)。 SearchBox有一个输入字段,应该将输入返回给父进程来处理事件。这工作正常,但当我回到方法handleSearch
中的父组件时,this.state...
未定义。
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>
);
}
这里也是我的SearchBox:
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>
);
}
}
答案 0 :(得分:0)
如果您的问题是如何从子组件获取父上下文,请尝试
class ParentComponent extends React.Component {
...
...
clickHandler(event){}
render(){
<ChildComponent parent={this}/>
}
}
class ChildComponent extends React.Component {
constructor(props){
super(props);
}
render(){
let parent = this.props.parent;
return <button onClick={parent.clickHandler}></button>
}
}
你会在这里收到错误
componentDidMount() {
$.get(PATH, function (result) {
this.setState({
books: result
});
}.bind(this));
}
因为回调函数中的this
没有引用组件的上下文。您应该将组件的上下文保存在变量
componentDidMount() {
let self = this;
$.get(PATH, function (result) {
self.setState({
books: result
});
}.bind(this));
}
最后决定是
constructor(props) {
super(props);
this.state = {books: []};
//add the following line into your code
this.handleSearch = this.handleSearch.bind(this);
}