首页 > 解决方案 > 与子交互时调用父 onPress 方法

问题描述

我想在按下子组件时触发父组件 onPress 方法和子组件 onPress 方法。

有没有办法在不将父母的方法传递给孩子的情况下做到这一点?

(这是因为我将它用作客户端组件的容器,而无需更改其代码)

例子:

这将同时触发console.log('parent pressed')}console.log('children pressed')}

        <Pressable style={{margin: 20, backgroundColor: 'red'}} onPress={() => console.log('parent pressed')}>
          <Button label={'press here'} onPress={() => console.log('children pressed')}/>
        </Pressable>

图片:

在此处输入图像描述

谢谢!

标签: react-native

解决方案


你可以做什么,你可以将相同的功能传递给父母/孩子。

eventAction = () => {console.log("result of both events")}

内部渲染()

<Pressable style={{margin: 20, backgroundColor: 'red'}} onPress={this.eventAction}>
              <Button label={'press here'} onPress={this.eventAction}/>
    </Pressable>

而且我认为 Pressable 内部不需要 Button 组件,您可以在其中使用 Text 组件。

编辑:

parentAction = () => {console.log("result of 1st events")}
childAction = () => {console.log("result of 2nd events")}


<Pressable style={{margin: 20, backgroundColor: 'red'}} onPress={()=>{this.parentAction()}}>
              <Button label={'press here'} onPress=onPress={()=>{this.parentAction(); this.childAction()}}/>
    </Pressable>

推荐阅读