【发布时间】:2019-01-21 23:17:53
【问题描述】:
目前我有 3 个组件:Child1、Child2 和 Parent。当按下Child2 中的按钮时,我想调用Child1 组件中的函数。
这是我迄今为止尝试过的,但我一直收到错误提示
this.refs.child.child2Function is not a function
处理这种情况的正确方法是什么(从另一个子组件调用一个子组件中的函数)?
我也在我的项目中使用redux。但是我的Child2 组件在多个选项卡中呈现。所以我无法使用redux 更新值,因为该值将在所有Child2 组件中更新。
Parent.js
class Parent extends Component{
parentFunction = () => {
console.log("This line gets printed. But the line below this breaks");
this.refs.child.child2Function();
}
render() {
return (
<View style={styles.pageContainer}>
<Child1 ref="child"/>
<Child2 parentFunc={this.parentFunction}/>
</View>
)}
Child2.js
class Child2 extends Component{
render() {
return (
<View style={styles.pageContainer}>
<Button
title="CLICK ME"
onPress={()=>this.props.parentFunc()} />
</View>
)}
Child1.js
class Child1 extends Component{
child1Function = () => {
console.log("Print this");
}
render() {
return (
<View style={styles.pageContainer}>
<Text>AAAA</Text>
</View>
)}
更新: 代码在此处设置的小吃示例中正常工作:https://snack.expo.io/rk4Y9RWUm
但是当我在我的 react 本机应用程序中有类似的解决方案时,我不断收到错误消息。我在此处包含了我的代码、控制台日志和错误消息的屏幕截图:https://drive.google.com/drive/folders/1RQYicEC_wqHKPRCs9pVsMZyuTxyiUbq2?usp=sharing
【问题讨论】:
-
为什么不将
child2Function移动到父级并在两个子级中从那里访问它? -
因为 child2Function 更新 child2 组件中的本地状态。此组件也用于其他不同的组件(基本上是 parent2,parent3,...)
-
console.log(this.refs.child)打印出什么?您可以在 codepen 上设置一个示例或其他东西供我们使用吗? -
我看不出有什么问题?代码按预期工作...codepen.io/anon/pen/gjJMYQ?editors=0010
-
@JohnRuddell 我设置了一个零食示例,它运行良好。但是当我在我的 react native 应用程序中做同样的事情时,我得到了一个错误。链接到 Snack:snack.expo.io/rk4Y9RWUm 链接到我的代码、console.log 和错误消息的屏幕截图:drive.google.com/drive/folders/…
标签: reactjs react-native react-redux components