[英]React native child component did not get componentWillReceiveProps from parents state
[英]How to get state of child component in react native
我有主要組件文件,並在另一個子組件中使用。 我必須獲取子組件的狀態。
例如:-主頁(父母)-表單(子項)組件我已經設置了處於狀態的任何文本框的值。 因此,我可以將Form組件的狀態值添加到主要組件中。
將功能作為道具傳遞給子組件
//Parent Component
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
this._handleChange = this._handleChange.bind(this);
}
_handleChange(e) {
const { name, value } = e.target;
this.setState({
[name]: value
});
}
render(){
return(){
<Form valueChange={this._handleChange} />
}
}
}
//Child Component
export default class Form extends Component {
render(){
return(){
<div>
<input type="email" name="username" onChange={(e) => this.props.valueChange()} value={username}/>
<input type="password" name="password" onChange={(e) => this.props.valueChange()} value={password}/>
</div>
}
}
}
通常,在React(和React-Native)中,信息從父組件傳遞到其子組件。 但是,如果您需要根據子組件的狀態更改父組件狀態的某些內容,則可以將一個函數傳遞給子組件,以執行此操作。
例如:
// Inside Parent Component
openModalFromParent() {
this.setState({ modalOpened: true });
};
// Passing Function to Child
<ChildComponent openModal={ this.openModalFromParent } />
// Inside Child Component
<TouchableHighlight onPress={ () => this.props.openModal() } />
在此示例中,子組件中的按鈕將觸發一個更改父組件狀態的功能-希望這會有所幫助!
在React中,您的狀態只能從父級流到子級。 您應該做的是將狀態從子級移到父級,然后將狀態作為道具傳遞給子級。
嘗試閱讀以下內容: https : //reactjs.org/docs/lifting-state-up.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.