react native学习笔记14——WebView的使用及与html通信

前端之家收集整理的这篇文章主要介绍了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的基本属性方法

基本属性

属性 类型 描述
source@H_403_57@ {uri: string,method: string,
headers: object,body: string},
{html: string,baseUrl: string},number@H_403_57@
在WebView中载入一段静态的HTML代码或是一个url(还可以附带一些 header 选项)@H_403_57@
automaticallyAdjustContentInsets@H_403_57@ bool@H_403_57@ 设置是否自动调整内容。@H_403_57@
contentInset@H_403_57@ {top:number,left:number,
bottom:number,right:number}@H_403_57@
设置网页内嵌边距。@H_403_57@
startInLoadingState@H_403_57@ bool@H_403_57@ 在第一次加载时是否显示loading视图。默认true。@H_403_57@
bounces(iOS)@H_403_57@ bool@H_403_57@ 指定滑动到边缘后是否有回弹效果。默认true。@H_403_57@
scalesPageToFit(iOS)@H_403_57@ bool@H_403_57@ 设置是否要把网页缩放到适应视图的大小,以及是否允许用户改变缩放比例。@H_403_57@
scrollEnabled(iOS)@H_403_57@ bool@H_403_57@ 设置是否开启页面滚动。@H_403_57@
domStorageEnabled(Android)@H_403_57@ bool@H_403_57@ 是否开启DOM存储。@H_403_57@
javaScriptEnabled(Android)@H_403_57@ bool@H_403_57@ 是否开启 JavaScript,在 iOS 中的 WebView 是默认开启的。@H_403_57@

基本方法

方法 描述
injectJavaScript@H_403_57@ 给WebView注入JS代码,注入后会立即执行。@H_403_57@
onNavigationStateChange@H_403_57@ 当导航状态发生变化的时候调用。@H_403_57@
onLoadStart@H_403_57@ 当网页开始加载的时候调用。@H_403_57@
onError@H_403_57@ 当网页加载失败的时候调用。@H_403_57@
onLoad@H_403_57@ 当网页加载结束的时候调用。@H_403_57@
onLoadEnd@H_403_57@ 当网页加载结束调用,不管是成功还是失败。@H_403_57@
renderLoading@H_403_57@ WebView组件正在渲染页面时触发的函数,只有 startInLoadingState 为 true 时该函数才起作用。@H_403_57@
renderError@H_403_57@ 监听渲染页面出错的函数。@H_403_57@
onShouldStartLoadWithRequest(iOS)@H_403_57@ 方法允许拦截 WebView 加载的 URL 地址,进行自定义处理。该方法通过返回 true 或者 false 来决定是否继续加载该拦截到请求。@H_403_57@

根据上面介绍的基本属性方法,我们在加载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。使用此方法我们可以自定义加载错误时的提示信息。
类似的renderLoading可以自定义加载显示的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发数据——postMessage

React Native向html发送数据可以通过postMessage方法实现。

  • React Native端
    设置WebView的ref属性,将组件view作为参数赋值给了this.webview
<WebView
        ref={(webview) => this.webview = webview}
        source={require('./messaging.html')}
    />

然后可通过postMessage方法从React Native向html发送数据

this.webview.postMessage('我是React Native发送过来的数据');
  • html端
    html端接收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发过来的数据——onMessage

React Native接收html发过来的数据可以通过onMessage方法实现。

  • html端
    html端通过调用window.postMessage给React Native发送数据。
document.getElementsByTagName('button')[0].addEventListener('click',function() {
      window.postMessage('这是html发送到RN的消息');
    });
  • React Native端
    当有html发送数据过来时会触发WebView的onMessage,在onMessage中处理接收到的数据。
<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

猜你在找的React相关文章