我正在开发我的第一个 React Native 应用程序。我想要实现的是从父组件执行一个子函数,这是这种情况:
孩子
export default class Child extends Component {
...
myfunct: function() {
console.log('Managed!');
}
...
render(){
return(
<Listview
...
/>
);
}
}
家长
export default class Parent extends Component {
...
execChildFunct: function() {
...
//launch child function "myfunct"
...
//do other stuff
}
render(){
return(
<View>
<Button onPress={this.execChildFunct} />
<Child {...this.props} />
</View>);
}
}
在这个例子中,当我按下父类中的按钮时,我想记录 'Managed!'
。怎么可行?
原文由 Pottercomuneo 发布,翻译遵循 CC BY-SA 4.0 许可协议
Nader Dabit 的答案已经过时,因为在 ref 属性中使用字符串文字 已被弃用。从 2017 年 9 月起,我们将这样做:
相同的功能,但不是使用字符串来引用组件,而是将其存储在全局变量中。