有没有办法在反应原生的Android应用程序中使视图组件(由JS编写)更新?

时间:2015-12-16 13:10:25

标签: android react-native

我使用react-native来构建一个Android应用程序,我想知道如何解决这种情况:在Java代码中,一些更新必须通知javascript刷新视图!

1 个答案:

答案 0 :(得分:0)

是的,这是可能的。此页面上有更多信息:

https://facebook.github.io/react-native/docs/native-modules-android.html#sending-events-to-javascript

您需要使用发射器在JavaScript中发回事件。

到目前为止,我还没有在实践中这样做,但我很快就会这样做。让我知道你是怎么办的。

在Java中使用他们的示例:

...
private void sendEvent(ReactContext reactContext,
                   String eventName,
                   @Nullable WritableMap params) {
  reactContext
  .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  .emit(eventName, params);
}
...
WritableMap params = Arguments.createMap();
...
sendEvent(reactContext, "keyboardWillShow", params); 

然后在你的JS中:

var { DeviceEventEmitter } = require('react-native');
...
var ScrollResponderMixin = {
  mixins: [Subscribable.Mixin],

  componentWillMount: function() {
  ...
  this.addListenerOn(DeviceEventEmitter,
                   'keyboardWillShow',
                   this.scrollResponderKeyboardWillShow);
  ...
  },
  scrollResponderKeyboardWillShow:function(e: Event) {
  this.keyboardWillOpenTo = e;
  this.props.onKeyboardWillShow && this.props.onKeyboardWillShow(e);
},

或者,您可以直接在JS中监听事件:

...
componentWillMount: function() {
     DeviceEventEmitter.addListener('keyboardWillShow', function(e: Event) {
      // handle event.
 });
}
...