gpt4 book ai didi

reactjs - 如何在 React Native 中监听子组件中的事件?

转载 作者:行者123 更新时间:2023-12-03 13:32:39 26 4
gpt4 key购买 nike

我想在我的 React Native 应用程序中实现从父组件到子组件的事件监听器,我使用 StackNavigator 作为路由器。

如何监听顶部/父组件中发生的事件?

最佳答案

只需使用 React Native 的 DeviceEventEmitter。从父组件发出事件,如下所示:

DeviceEventEmitter.emit('eventKey', {name:'John', age:23});

并在子组件中监听事件

componentDidMount(){
//add listener
this.eventListener = DeviceEventEmitter.addListener('eventKey',this.handleEvent);
}

handleEvent=(event)=>{
//Do something with event object
}

componentWillUnmount(){
//remove listener
this.eventListener.remove();
}

关于reactjs - 如何在 React Native 中监听子组件中的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47334073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com