1.react-native 和 H5通信的情景
首先如果你的项目中需要接入一个H5写的项目,但是这个服务有必须用到react-native中的服务比如打开摄像头,获取地理位置等等。但是这些数据在H5中是获取不到的,那么就需要和react-native通信,在react-native中获取到想要的数据,然后将数据返回给H5。
2.实现方式
(1).通过android原生和ios原生可以实现和H5的通信。
(2).通过react-native中的webview来实现和H5通信。
(3).通过第二种方式实现:
在webview中onMessage是用来监听H5发送的消息的,我们可以在onMessage中接受到请求的数据。
例如:
<WebView
onMessage={
(data)=>{console.log(data);}
}
/>
在 rn中通过webview的postMessage给H5返回结果。
例如:
<WebView
ref={ (webview) => {this.web=webvew;} }
/>
handleResponse=(response)=>{
this.web.postMessage(response);
}
H5中可以通过window.ReactNativeWebView.postMessage()向rn中发送消息。
例如:
function(request){
window.ReactNativeWebView.postMessage(request);
}