我知道这是一个非常普遍的问题,但是我在互联网上发现的一些答案已被弃用。您如何在2020年从父组件中调用子组件的方法?我的实际代码是这样的,但是不起作用
儿童:
export default class CustomComp extends React.Component{
exampleMethod = () => {
console.log('pressed');
};
render(){
return (
...
);
}
}
父母:
export default class App extends React.Component{
child = CustomComp;
render(){
return (
<View style={styles.container}>
<Button title="Press" onPress={this.child.exampleMethod} />
<CustomComp ref={child => {this.child = child}} {...this.props} />
</View>
);
}
}
您必须将函数作为回调调用。
export default class App extends React.Component{
render(){
return (
<View style={styles.container}>
<Button title="Press" onPress={() => this.child.exampleMethod()} />
<CustomComp ref={child => {this.child = child}} {...this.props} />
</View>
);
}
}