嗨我目前正在reactjs,但在非常基本的水平。我试图解析从父母到孩子以及孩子到父母的数据。父母对孩子正常工作,但是我不能。如何使用reactjs将数据从子项解析到父项?
这里是整个场景... 我有3个组件..应用程序,家庭和用户。 从App组件到Home组件我想解析数据。它工作正常。 在家庭组件我有一个输入字段。如果我写了一些内容并单击按钮,则输入值将解析为App组件。应用程序是我的父母和家庭是孩子..
这里是代码... APP组件
constructor() {
super()
this.state = {
userName : ' '
};
}
changeUName(newName) {
this.setState({
userName: newName
});
console.log('user',newName); // Getting Undefined
}
render() {
return (
<div className="App">
<Home changeUser = {() => this.changeUName()} />
</div>
);
}
子组件用户
constructor(props) {
super();
this.state = {
userName: ''
};
}
changeUName(event) {
this.setState({
userName: event.target.value
});
}
nameChange() {
console.log(this.state.userName) // If I write "Test" in input field. I will get the value here.
this.props.changeUser(this.state.userName); // Once I parse this value, I am getting undefined..
}
render() {
return(
<div>
<h1> HOME Page</h1>
Name : <input type="text" value={this.state.userName} onChange={(event) => this.changeUName(event)} ref="uName"/><br/>
<button onClick={() => this.nameChange()}>Click</button>
</div>
)
}
我不知道它是怎么了。请指导我。在此先感谢..
的可能的复制[如何传递数据从子组件到其在ReactJS中的父代?](http://stackoverflow.com/q uestions/38394015/how-to-pass-data-from-child-component-to-parent-in-reactjs) –
谢谢@Shubham。我看过这篇文章。自昨天以来尝试了很多,但仍显示未定义的价值。 –