在 React Native 中从父组件调用子函数 [英] Call child function from parent component in React Native
问题描述
我正在开发我的第一个 React Native 应用程序.我想要实现的是从父组件执行子函数,情况是这样的:
I'm developing my first React Native app. What I'm trying to achieve is to execute a child function from the parent component, this is the situation:
儿童
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!'
.可行性如何?
In this example, I would like to log 'Managed!'
when I press the button in the parent class. How is it feasible?
推荐答案
Nader Dabit 的回答已经过时,因为在 ref 属性中使用字符串文字 已弃用.这是我们截至 2017 年 9 月的做法:
Nader Dabit's answer is outdated, since using String literals in ref attributes has been deprecated. This is how we would do it as of September 2017:
<Child ref={child => {this.child = child}} {...this.props} />
<Button onPress={this.child.myfunc} />
相同的功能,但不是使用字符串来引用组件,而是将其存储在全局变量中.
Same functionality, but instead of using a String to reference the component, we store it in a global variable instead.
这篇关于在 React Native 中从父组件调用子函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!