[英]How to pass data between child and parent in react-native?
module.exports= class APP extends React.Component {
constructor(props){
super(props);
this.state = {
key1:'key1',
key2:'key2'
};
render() {
return (
<View>
<Button
onPress={this.goToTisch}>
1
</Button>
<Button
onPress={this.goToTisch}>
2
</Button>
</View>
);
}
}
我只是用react-native編寫一個應用程序,並且不知道如何從子元素更新父狀態。 先感謝您
您需要從父級傳遞給子級回調函數,然后在子級中調用它。
例如:
class Parent extends React.Component {
constructor(props){
super(props);
this.state = {
show: false
};
}
updateState = () => {
this.setState({
show: !this.state.show
});
}
render() {
return (
<Child updateState={this.updateState} />
);
}
}
class Child extends React.Component {
handleClick = () => {
this.props.updateState();
}
render() {
return (
<button onClick={this.handleClick}>Test</button>
);
}
}
要從子級調用父級方法,您可以像這樣傳遞引用。
家長班
<ChildClass
onRef={ref => (this.parentReference = ref)}
parentReference = {this.parentMethod.bind(this)}
/>
parentMethod(data) {
}
兒童班
let data = {
id: 'xyz',
name: 'zzz',
};
//這將調用parent的方法
this.props.parentReference(data);
使用像這樣的道具:
上級:
<Parent>
<Child onChange={this.change} />
</Parent>
兒童:
<button onclick={this.props.onChange('It Changed')} />
這樣,您就可以在父母中做任何您想做的事情。
這可以通過兩種方式實現:
父組件:
//Needs argument
const addGoalHandler = goalTitle => {
// code for updating state
}
<GoalInput onAddGoal={this.addGoalHandler} />
子組件:
方法1:使用香草Javascript
<Button
title="ADD"
onPress={props.onAddGoal.bind(this, enteredGoal)}
/>
方法2:使用箭頭功能
<Button
title="ADD"
onPress={() => { props.onAddGoal(enteredGoal) } }
/>
class Parent extends Component{
constructor(props){
super(props);
this.state={value:''};
this.getData=this.getData.bind(this);
}
getData(val){
console.log(val);
this.setState({
value:val
});
}
render(){
const {value}=this.state
return(
<View>
<Screen sendData={this.getData}/>
<View>
<Text>
{this.state.value};
</Text>
</View>
</View>
)
}
}
export default Parent;
CHILD CLASS:
class Child extends Component{
componentWillMount(){
this.props.sendData('data');
}
render(){
return(
<View>
</View>
)
}
}
export default Child;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.