javascript - 无法从 React Native 中的父组件调用子组件方法
问题描述
我有一个<Parent>
包含组件的 React Native 组件<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)
。
有任何想法吗?
谢谢!
解决方案
您可以在构造函数中使用创建一个 ref并使用propReact.createRef
将其分配给子组件实例ref
发布您可以使用访问孩子的帖子this.child.current
示例代码:
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 参考
this.child.current.getWrappedInstance()
推荐阅读
- node.js - 在 Express.js 中验证 Todoist Webhook API 的请求负载
- reactjs - 从服务器获取后无法在 Reactjs 中编辑表单字段
- c# - LINQ 从深度子菜单 id 的集合构建树
- javascript - 查找 .closest() 失败
- reactjs - React document.removeEventListener 不起作用
- android - Spinner 在括号中接收数据
- javascript - 按两个元素和总和值对数组对象进行分组(Javascript)
- modx - 为什么 modx 不注册 js 和 css
- wcf - WCF 方法在生产中返回 400 Bad Request
- r - 如何从R中的行中删除最后的观察结果