use*_*105 9 javascript 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我只是用react-native编写一个应用程序,不知道如何从子元素更新父状态.先感谢您
Pio*_*łek 19
您需要从父级回传到子回调函数,然后在子级中调用它.
例如:
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
要从子级调用父级方法,您可以像这样传递引用。
家长班
<ChildClass
onRef={ref => (this.parentReference = ref)}
parentReference = {this.parentMethod.bind(this)}
/>
parentMethod(data) {
}
Run Code Online (Sandbox Code Playgroud)
儿童班
let data = {
id: 'xyz',
name: 'zzz',
};
Run Code Online (Sandbox Code Playgroud)
//这将调用parent的方法
this.props.parentReference(data);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18426 次 |
| 最近记录: |