最新消息:从今天开始,做一个有好习惯的人。

react-native模块直接的监听(非与原生)

其他 迷路的老鼠 5303浏览 4评论

和原生之间的通信前面说了,这里只说react-native模块间的通信,适用情况与参数传递不一样,这个模块间可能并没有直接关联,比如后台监听进程监听到更新等。
react-native实例化了一个EventEmitter,封装成RCTDeviceEventEmitter,通过RCTDeviceEventEmitter建立监听并回调处理方法。
核心的东西牵扯太多,这里直接上demo。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');

var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');

var {
  StyleSheet,
  Text,
  View,
  TextInput
} = React;


var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});


var Input = React.createClass({

    handleUpdateChange(text) {
        RCTDeviceEventEmitter.emit('change',text);
    },


  render() {

    return (
      <View style={{justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF'}}>
        <TextInput onChangeText={(text) => this.handleUpdateChange(text)} style={{ width : 200, height: 40, borderColor: 'gray', borderWidth: 1}} />
      </View>
    );
  }
});




var ShowText = React.createClass({

    getInitialState(){
      return {
        text : ''
      }
    },

    componentDidMount(){
      var me = this;
      RCTDeviceEventEmitter.addListener('change',function(text){
         me.setState({
          text : text
         })
      })
    },


    render() {
        return (
          <View style={{justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF'}}>
            <Text>{this.state.text}</Text>
          </View>
        );
    }
});

module.exports = React.createClass({


  render() {
    return (
      <View style={styles.container}>
        <Input />
        <ShowText />
      </View>
    );
  }
});</pre>

fb273ef29cf057a236290c437f325ef1

转载请注明:迷路的老鼠 » react-native模块直接的监听(非与原生)

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (4)

  1. color#333333是啥颜色,23333~´∀`
    wa9年前 (2015-12-20)回复
    • 到网上找个取色器,瞧一下
      admin9年前 (2015-12-21)回复
      • 黑色~嘻嘻 #FFFF66也很好看啊,灭哈哈哈~
        wa9年前 (2015-12-21)回复
        • ... 有做程序猿的潜质
          admin9年前 (2015-12-22)回复