react native学习笔记14——WebView的使用及与html通信
加载一个在线网页下例是一个最简单的WebView的使用,给定一个url网址,用WebView加载渲染出来。 import React,{ Component } from 'react';
import { WebView } from 'react-native';
export default class WebViewSimpleDemo extends Component {
render() {
return (
<WebView source={{uri: 'http://blog.csdn.net/column/details/17061.html'}} /> ); } }
效果图: 通常项目中使用WebView并不是简单的加载一个静态网页,例如显示一个加载页,提供一个统一的加载失败页,webview如何与rn双向通讯等。为了能完成上述需求,我们还需要学习WebView的基本属性和方法。 基本属性
基本方法
根据上面介绍的基本属性方法,我们在加载WebView中增加加载中和加载失败的页面显示。 <WebView source={{uri: 'http://blog.csdn.net/column/details/17061.html'}} renderError={() => { console.log('renderError') return <View><Text>renderError</Text></View> }} renderLoading={() => { return <View><Text>自定义Loading...</Text></View> }} />
renderError加载错误时会回调该函数,显示该函数返回的View。使用此方法我们可以自定义加载错误时的提示信息。 加载本地静态html文件import React,{ Component } from 'react';
import { WebView } from 'react-native';
export default class WebViewSimpleDemo extends Component {
render() {
return (
<WebView source={require('./helloworld.html')} /> ); } }
helloworld.html <!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=320,user-scalable=no">
<style type="text/css"> body { margin: 0; padding: 0; font: 62.5% arial,sans-serif; background: #ccc; } h1 { padding: 45px; margin: 0; text-align: center; color: #f33; } </style>
</head>
<body>
<h1>hello world!</h1>
</body>
</html>
效果图: React Native与Html通信React Native向html发数据——postMessageReact Native向html发送数据可以通过postMessage方法实现。
<WebView
ref={(webview) => this.webview = webview}
source={require('./messaging.html')}
/>
然后可通过postMessage方法从React Native向html发送数据 this.webview.postMessage('我是React Native发送过来的数据');
var messagesReceivedFromReactNative = 0;
document.addEventListener('message',function(e) {
messagesReceivedFromReactNative += 1;
document.getElementsByTagName('p')[0].innerHTML =
'从React Native接收的消息: ' + messagesReceivedFromReactNative;
document.getElementsByTagName('p')[1].innerHTML = e.data;
});
React Native接收html发过来的数据——onMessageReact Native接收html发过来的数据可以通过onMessage方法实现。
document.getElementsByTagName('button')[0].addEventListener('click',function() {
window.postMessage('这是html发送到RN的消息');
});
<WebView
ref={(webview) => this.webview = webview}
source={require('./messaging.html')}
onMessage={this._onMessage}
/>
//接收HTML发出的数据
_onMessage = (e) => {
Alert.alert(e.nativeEvent.data);
}
效果图 React Native与Html通信的完整代码在Github (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |