react-native - 与子交互时调用父 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>
图片:
谢谢!
解决方案
你可以做什么,你可以将相同的功能传递给父母/孩子。
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>
推荐阅读
- swift - 如何以编程方式设置控制图像视图宽度的滑块
- oracle - 如何从oracle数据库中提取数据并保存在谷歌云平台
- firebase - 为 Google Analytics(分析)网络 + 应用程序属性安排电子邮件报告
- django - 位置参数缺少“状态”
- java - 如何让 Spring Tools Suite 识别 spring 注释
- mongodb - Mongo DB中基于光标的分页,其中跳过或限制未知
- laravel - 如何在 plesk 服务器上处理 SQLSTATE[HY000] [1045] 错误?
- javascript - 使用 HTML、CSS 和 JS 的侧边栏中的多级下拉菜单
- elixir - 模块执行时如何将当前上下文带入模块中?
- linux - 如何检查文件是否来自 tmpfs 内存缓存或磁盘缓存