我有一个 React Native 组件 <Parent>
包含一个组件 <Child>
,并且我希望能够在 Parent 中调用 Child 的方法之一。在阅读了一堆其他帖子之后,这就是我所拥有的:
Child.js
export default class Child extends Component {
method1() {
console.log("success");
}
render() {
return(
<View/>
)
}
}
父级
export default class Parent extends Component {
render() {
return(
<View>
<TouchableOpacity
onPress={() => this.child.method1()}
/>
<Child
onRef={ref => (this.child = ref)}
/>
</View>
)
}
}
我收到错误消息“_this2.child.method1 不是函数。”
我尝试过的其他东西正在使用 refInput
而不是 onRef
,并做 ref => {this.child = ref}
而不是 ref => (this.child = ref)
.
有什么想法吗?
谢谢!
最佳答案
您可以在构造函数中使用 React.createRef
创建一个 ref,并使用 ref
prop 将其分配给子组件实例
发布您可以使用 this.child.current
访问 child
示例代码:
class Child extends React.Component {
myMethod() {
console.log("myMethod called");
}
render() {
return <Text>This is child</Text>;
}
}
class App extends Component {
constructor() {
super();
this.child = React.createRef();
}
render() {
return (
<View style={styles.app}>
<View style={styles.header}>
<Image
accessibilityLabel="React logo"
source={{ uri: logoUri }}
resizeMode="contain"
style={styles.logo}
/>
<Text style={styles.title}>React Native for Web</Text>
</View>
<Child ref={this.child} />
<Button
onPress={() => {
this.child.current.myMethod();
}}
title="Example button(Click to trigger Child)"
/>
</View>
);
}
}
如果你的子组件通过 redux 的 connect 连接,你仍然可以通过在 connect 中将 withRef 选项设置为 true 来访问 childRef
connect(mapStateToProps, mapDispatchToProps, null, { withRef: true })(Child);
如果您使用的是 v6 或更高版本的 redux,请设置 forwardRef 属性而不是 withRef
connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true })(Child);
一旦你在父级中这样做,你就可以使用
访问 cchild refthis.child.current.getWrappedInstance()
关于javascript - 无法从 React Native 中的父组件调用子组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55202209/