React Native - initialProperties Android
Я работаю под React-Native, и я ищу прохождение первого реквизита JS через Java. Это можно сделать легко в Objective-C с initialProperties следующим образом:
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"myapp"
initialProperties:initialProperties
launchOptions:launchOptions];
Где initialProperties - это NSDictionary
, который будет преобразован в JSON и доступен в JS через this.props
.
Поэтому я хочу сделать то же самое в Android. Любая помощь? Благодаря
Ответы
Ответ 1
В Android вы можете передать initialProperties
с помощью launchOptions
в качестве связки.
Как упоминается здесь в исходном коде: https://github.com/facebook/react-native/blob/7377fdcc70b25eb023e7c6d1b37eeae2a700cb88/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java#L325-L334
Итак, вы можете сделать что-то вроде этого:
Bundle initialProps = new Bundle();
initialProps.putString("myKey", "myValue");
mReactRootView.startReactApplication(mReactInstanceManager, "MyAwesomeApp", initialProps);
Ответ 2
getlauchOptions был перемещен внутри ReactActivityDelegate, теперь я использую этот код:
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "myAppName";
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
@Nullable
@Override
protected Bundle getLaunchOptions() {
Bundle initialProps = new Bundle();
initialProps.putString("SOME_VARIABLE_1", BuildConfig.SOME_VARIABLE_1);
initialProps.putString("SOME_VARIABLE_2", "some variable 2 value");
return initialProps;
}
};
}
Ответ 3
В ответ на native-v0.20 вы можете переопределить метод getLaunchOptions
в файле MainActivity.java
.
@Override
protected Bundle getLaunchOptions() {
Bundle opts = new Bundle();
opts.putBoolean("someValue", true);
return opts;
}
Это позволит вам получить доступ к someValue
из реквизита вашего основного приложения:
class App extends React.Component {
static propTypes = {
someValue: PropTypes.bool,
};
render() {
return <SomeComponent someValue={this.props.someValue} />;
}
}
AppRegistry.registerComponent('App', () => App);
Ответ 4
Соблюдайте осторожность, это устаревает в реакции-native > 0.34
https://github.com/facebook/react-native/pull/9320
это сообщение фиксации:
Move `getLaunchOptions` from ReactActivity to ReactActivityDelegate
Summary:
After 3c4fd42, `getLaunchOptions` no longer exists in class `ReactActivity`.
We need refactor UIExplorerActivity to fix the build error.
Closes #9320
Differential Revision: D3696381
Pulled By: astreet
fbshipit-source-id: 5700cf2363029a95cfbdaf6230e4f82ea69fb472
master (#2) v0.34.0-rc.0
Таким образом, вам нужно будет изменить эту часть своего кода, если вы обновите свою версию реакции, и поскольку вы переопределяете метод, который не будет существовать в родительском классе, вы можете не попасть в какое-либо сообщение об ошибке, будет трудно отлаживать
Ответ 5
Все ответы здесь казались немного устаревшими. С React-Native 0.42 это сработало для меня.
В вашем классе Activity (not Application) сделайте это
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, "My Cool App") {
@Nullable
@Override
protected Bundle getLaunchOptions() {
Bundle bundle = new Bundle();
if( MainActivity.this.port != null ) {
bundle.putInt("port", MainActivity.this.port);
}
return bundle;
}
};
}
Очевидно, замените "порт" на то, что вы хотите передать в реквизиты основного основного компонента React.
Ответ 6
Обновление для реакции-нативного> 0.59.0 необходимо переопределить ReactActivityDelegate в MainActivity.java
Пример
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
public class RNTesterActivity extends ReactActivity {
public static class RNTesterActivityDelegate extends ReactActivityDelegate {
public RNTesterActivityDelegate(ReactActivity activity, String mainComponentName) {
super(activity, mainComponentName);
}
@Override
protected Bundle getLaunchOptions() {
// YOUR PROPS
Bundle props = new Bundle();
props.putString("key1", "string");
props.putInt("key2", 5);
return props;
}
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new RNTesterActivityDelegate(this, getMainComponentName());
}
@Override
protected String getMainComponentName() {
return "RNTesterApp";
}
}