我关注了this answer将 Prop 从子组件传递到父组件,效果很好。
当我提交表单时,我的子组件中的响应状态良好 但问题是,我必须提交表单两次才能在我的 parent 组件中获取 props searchString。
如果我在子组件中的这一行执行 console.log
this.props.getSearchString(this.getSearch());
提交时我得到未定义
你知道问题出在哪里吗?
我的父组件
class Parents extends Component {
constructor() {
super();
this.state = { searchString :'' };
}
setSearchString(string) {
this.setState({ searchString: string });
}
render() {
return (
<div>
<p>Get Search String: {this.state.searchString}</p>
<Child getSearchString={ mySearch => this.setSearchString(mySearch)} />
</div>
)
}
}
我的 child 组件
class Child extends Component {
constructor(props) {
super(props);
this.state = {value: '', response: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
getSearch() {
return this.state.response;
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
this.setState({response: this.state.value});
this.props.getSearchString(this.getSearch());
}
render() {
return (
<div>
<p>Response: {this.state.response}</p>
<form className="searchForm" onSubmit={this.handleSubmit}>
<input type="text"
className="searchInput"
value={this.state.value}
onChange={this.handleChange} />
<button className="searchButton" type="submit">Ok</button>
</form>
</div>
)}
}
最佳答案
不要给子组件提供参数。
<Child getSearchString={ () => this.setSearchString()} />
关于javascript - react 将 Prop 从子级传递给父级未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46489608/