React-Native传值方式之 :DeviceEventEmitter添加监听控制并传值到其他页面
在 native 开发中,我们可以使用广播实现事件的订阅和事件的触发,从而实现不在该页面但是可以调用该页面的方法。
在 React Native 中,我们也可以使用 DeviceEventEmitter 实现类似的功能
该方法是官方 API,调用时,直接引用就行了。
1 import {DeviceEventEmitter} from 'react-native'; 2 //… 3 //调用事件通知 4 DeviceEventEmitter.emit('xxxName’,param); 5 //xxxName:通知的名称 param:发送的消息(传参)
如果我们要实现
- 在A页面:点击按钮传递参数到B页面
- 在B页面:使用接收的参数刷新列表
操作如下
- 在B页面实现事件的监听,假设我们将事件命名为 refreshListListener
componentDidMount(){ var self = this; this.listener =DeviceEventEmitter.addListener('xxxName',function(param){ // use param do something }); } //xxxName:通知的名称 param:接收到的消息(传参) componentWillUnmount(){ this.listener.remove(); } //在componentWillUnmount 内需要我们手动移除通知
- 在A页面中,发送消息,触发B页面订阅的事件
<TouchableOpacity onPress={() => { DeviceEventEmitter.emit('refreshListListener', {name: 'jerry', age: 100}); } }> <Text>刷新B页面的列表</Text> </TouchableOpacity>