我想将props
从JavaScript传递到本机模块。
我将如何在代码中实现这一点?
这是一个最小的例子
ToastModul.java
... imports
public class ToastModule extends ReactContextBaseJavaModule {
@Override
public String getName() {
return "ToastExample";
}
@ReactMethod
public void show(String message, int duration) {
Toast.makeText(getReactApplicationContext(), message, duration).show();
}
public ToastModule(ReactApplicationContext reactContext) {
super(reactContext);
}
}
ToastModulPackage.java
... imports
public class CustomToastPackage implements ReactPackage {
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ToastModule(reactContext));
return modules;
}
}
ToastExample
import {
NativeModules
} from 'react-native';
module.exports = NativeModules.ToastExample;
App.js
... imports
import ToastExample from "./bridge/ToastExample.js"
type Props = {};
export default class App extends Component<Props> {
sendMessageToNative() {
ToastExample.show("Foo Bar", 1);
}
render() {
return (
<View style={styles.container}>
<Text>Don't Push It</Text>
<Button
onPress={() => this.sendMessageToNative()}
title={Dont't} /
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
如您所见,我能够将功能参数从JS - React Native
传递到Java - Native
(请参阅:ToastExample.show("Foo Bar", 1);
)。
如果我想将自定义props
从JS - React Native
传递到Java - Native
怎么办?
是否有一种方法可以在不使用ToastExample
制作自定义组件的情况下实现?还是只能通过在JS - React Native
网站上调用另一个函数,在setter
端调用Java - Native
方法来实现?