gke*_*ley 5 javascript reactjs react-native
我有一个<Parent>包含组件的 React Native 组件,<Child>我希望能够在 Parent 中调用 Child 的方法之一。在阅读了一堆其他帖子后,这就是我所拥有的:
儿童.js
export default class Child extends Component {
method1() {
console.log("success");
}
render() {
return(
<View/>
)
}
}
Run Code Online (Sandbox Code Playgroud)
家长
export default class Parent extends Component {
render() {
return(
<View>
<TouchableOpacity
onPress={() => this.child.method1()}
/>
<Child
onRef={ref => (this.child = ref)}
/>
</View>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误“_this2.child.method1 不是函数。”
我尝试过的其他事情是使用refInput而不是onRef,而ref => {this.child = ref}不是ref => (this.child = ref)。
有任何想法吗?
谢谢!
您可以React.createRef在构造函数中使用创建一个 ref并使用refprop将其分配给子组件实例
发布您可以使用访问孩子的帖子 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你的子组件连接了来自 redux 的 connect,你仍然可以通过在 connect 中将 withRef 选项设置为 true 来访问 childRef
connect(mapStateToProps, mapDispatchToProps, null, { withRef: true })(Child);
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 v6 或更高版本的 redux,请设置 forwardRef 属性而不是 withRef
connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true })(Child);
Run Code Online (Sandbox Code Playgroud)
Once you do that in the parent you will be able to access the cchild ref with
this.child.current.getWrappedInstance()
Run Code Online (Sandbox Code Playgroud)
实现此目的的一种方法是将函数向下传递给子级,子级可以将函数传递给该子级。例如:
<TouchableOpacity
onPress={() => this.childFunc()}
/>
<Child addMethod={func => this.childFunc = func}/>
Run Code Online (Sandbox Code Playgroud)
props.addFunc(this.method1)然后从孩子内部调用。只要确保你的this是你想要的那个。
但更重要的是,您应该首先问自己为什么需要这样做。
| 归档时间: |
|
| 查看次数: |
3021 次 |
| 最近记录: |