[英]react pass props from child to parent undefined
我按照这个答案将道具从孩子传递到父组件,并且效果很好。
提交表单时,我的子组件中的响应状态很好,但是问题是,我必须提交表单两次,才能在父母组件中获得道具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>
)
}
}
我的孩子组件
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()} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.