是否可以在React Native中的 webView 内运行React,其方式是React(非本机代码)代码仍然可以与本机应用程序通信?
这样做的原因是,虽然我的应用程序的某些方面需要React Native的性能等优点,但大多数方面都可以在 WebView 内运行,我真的很好希望避免重写呈现给DOM的内容。
我还会以某种方式向 WebView 中的JS公开一个桥对象,即:
nativeBridge.doSomethingThatBrowserCant();
答案 0 :(得分:3)
是的,this package完全符合您的需要。
基本上,您是从WebView
向React Native发送消息,然后您可以使用它们执行所需的操作。这些消息是简单的字符串,但您可以使用JSON.stringify
发送更复杂的数据。
const injectScript = `
(function () {
if (WebViewBridge) {
WebViewBridge.onMessage = function (message) {
if (message === 'native.didSomething') {
// Domething was done inside of React Native.
console.log('native.didSomething');
}
};
WebViewBridge.send('native.doSomething');
}
}());
`;
class Example extends Component {
doSomething() {
// Do something inside of React Native.
this.refs.webviewbridge.sendToBridge('native.didSomething');
}
onBridgeMessage(message) {
const {webviewbridge} = this.refs;
if (message === 'native.doSomething') {
this.doSomething();
}
}
render() {
return (
<WebViewBridge
ref="webviewbridge"
onBridgeMessage={this.onBridgeMessage.bind(this)}
injectedJavaScript={injectScript}
source={{uri: "http://google.com"}}
/>
);
}
}