This article mainly introduces the sample code for communication between react native and webview. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
WebView is a component in ReactNative. It can create a native WebView that can be used to access a web page.
Sometimes we need to RN communicates with WebView, or transmits data, or sends message notifications. At this time, the following knowledge must be used.
1: WebView to RN Send data from the end:
First, we build a webview:
##
{ this.handleMessage(e) }} />
handleMessage(e) { this.setState({webViewData: e.nativeEvent.data}); }
var data = 0; function sendData(data) { if (window.originalPostMessage) { window.postMessage(data); } else { throw Error('postMessage接口还未注入'); } } document.getElementById('button').onclick = function () { data += 100; sendData(data); }
Two: RN sends data to Webview:
sendMessage() { this.refs.webview.postMessage(++this.data); }
Just write the data you want to send as a parameter in this method.
window.onload = function () { document.addEventListener('message', function (e) { document.getElementById('data').textContent = e.data; }); }
收到react native发送的数据:
/** * Created by 卓原 on 2017/8/17. * zhuoyuan93@gmail.com */ import React from 'react'; import { View, Text, StyleSheet, WebView } from 'react-native'; export default class Web extends React.Component { constructor(props) { super(props); this.state = { webViewData: '' } this.data = 0; } sendMessage() { this.refs.webview.postMessage(++this.data); } handleMessage(e) { this.setState({webViewData: e.nativeEvent.data}); } render() { return () } } const styles = StyleSheet.create({ container: { flex: 1, marginTop: 22, backgroundColor: '#F5FCFF', }, }); { this.handleMessage(e) }} /> 来自webview的数据 : {this.state.webViewData} { this.sendMessage() }}>发送数据到WebView
The above is the detailed content of Detailed explanation of communication examples between react native and webview. For more information, please follow other related articles on the PHP Chinese website!