美文网首页react-native
react-native-webview 和H5之间的交互最新总

react-native-webview 和H5之间的交互最新总

作者: 与世倾听X游定终生 | 来源:发表于2019-08-28 15:14 被阅读0次

爬了N个坑,终于打通了react-native-webview和H5之间的数据交互:

RN发送数据给H5:

<Button style={styles.buttonStyle} title='发送消息' onPress={this._sendMessage}/>

_sendMessage = () => { 

   let data = {"type":"friends"};

 if (this.webview) {

console.log('------->jsonStr'+JSON.stringify(data));

this.webview.postMessage(JSON.stringify(data));

}}

问题在于H5端接收数据问题:

//注册事件 接收数据(这里网上很多写成window.document,并不能监听到方法)

window.addEventListener('message', function(e) {

const message = e.data;//字符串类型

  console.log('WebView message:',message);

// alert(message);

})

H5数据传递给RN:

网上到处都是使用

window.postMessage('*****')方法,但是RN端并不能接收到数据

最终进到https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#communicating-between-js-and-native

才发现是这么写才有效:

window.ReactNativeWebView.postMessage(str);

最终只需要在RN端配置WebView的onMessage方法即可:

相关文章

网友评论

    本文标题:react-native-webview 和H5之间的交互最新总

    本文链接:https://www.haomeiwen.com/subject/gwzpectx.html