如何从本地android传递数据以响应本地?

Sil*_*Sil 5 android react-native

我想从本地android Main Activity类传递一个字符串值来响应本地组件。我应用了此代码,但是一旦我在日志中打印“数据”,它就会显示未定义。我无法理解问题所在。我是React Native的初学者。提前致谢。

在主要活动中:

@Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected Bundle getLaunchOptions() {

                Bundle initialProperties = new Bundle();
                initialProperties.putString("var_1","Im the first var");
                return initialProperties;
            }
        };
    }
Run Code Online (Sandbox Code Playgroud)

在App.js中:

export default class App extends Component<Props> {

  render() {
    var data = this.props.var_1;
    console.log(data);
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.welcome}>{this.props.var_1}</Text> 
      </View>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Coo*_*ol7 9

有几种方式:

您可以通过从 android 活动发出事件来发送它,并在您的反应组件中处理该事件。

    //Emitting the event from Android Activity.

    public class MainActivity extends ReactActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            WritableMap map = Arguments.createMap();
            map.putString("key1", "Value1");
            map.putString("key1", "Value1");

        try {
           getReactInstanceManager().getCurrentReactContext()   
          .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
          .emit("customEventName", map);

            } catch (Exception e){
              Log.e("ReactNative", "Caught Exception: " + e.getMessage());
            }
        }
Run Code Online (Sandbox Code Playgroud)

并在反应组件 addEventListner(subscribe) 到该事件,如:

import { DeviceEventEmitter } from 'react-native';

componentWillMount: function() {
  DeviceEventEmitter.addListener('customEventName', function(e: Event) {
    // handle event and you will get a value in event object, you can log it here
  });
}
Run Code Online (Sandbox Code Playgroud)

另一种方式是:

您可以将该字符串存储在 SharedPreferences 中,并且可以从 React-native 组件访问相同的值。有关共享首选项的使用,请参阅以下链接:https : //github.com/sriraman/react-native-shared-preferences