嗨我目前正在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。我看過這篇文章。自昨天以來嘗試了很多,但仍顯示未定義的價值。 –