发布于 4年前

React Native 根据WebView内容自动设置高度

插件路径:https://github.com/xiehui999/react-native-webview-plugin

不想安装插件,可直接创建MyWebView.js文件

1、MyWebView.js

/**

* Custom WebView with autoHeight feature

*

* @prop source: Same as WebView

* @prop autoHeight: true|false

* @prop defaultHeight: 100

* @prop width: device Width

* @prop ...props

*/

import React, { Component }from 'react';

import {

View,

Dimensions,

WebView,

Platform,

}from 'react-native';

const injectedScript =function() {

function waitForBridge() {

if (window.postMessage.length !==1){

setTimeout(waitForBridge,200);

}

else {

postMessage(

Math.max(document.documentElement.clientHeight,document.documentElement.scrollHeight,document.body.clientHeight,document.body.scrollHeight)

)

}

}

waitForBridge();

};

export default class MyWebViewextends Component {

state = {

webViewHeight: Number

};

static defaultProps = {

autoHeight:true,

}

constructor (props: Object) {

super(props);

this.state = {

webViewHeight:this.props.defaultHeight

}

this._onMessage =this._onMessage.bind(this);

}

_onMessage(e) {

this.setState({

webViewHeight:parseInt(e.nativeEvent.data)

});

}

stopLoading() {

this.webview.stopLoading();

}

reload() {

this.webview.reload();

}

render () {

const _w =this.props.width ||Dimensions.get('window').width;

const _h =this.props.autoHeight ?this.state.webViewHeight :this.props.defaultHeight;

const androidScript ='window.postMessage = String(Object.hasOwnProperty).replace(\'hasOwnProperty\', \'postMessage\');' +

'(' + String(injectedScript) +')();';

const iosScript ='(' + String(injectedScript) +')();' +'window.postMessage = String(Object.hasOwnProperty).replace(\'hasOwnProperty\', \'postMessage\');';

return (

<WebView

ref={(ref) => {this.webview = ref; }} injectedJavaScript={Platform.OS ==='ios' ?iosScript :androidScript} scrollEnabled={this.props.scrollEnabled ||false} onMessage={this._onMessage} javaScriptEnabled={true} automaticallyAdjustContentInsets={true} {...this.props} style={[{width:_w},this.props.style, {height:_h}]} />

)

}

}

2、页面使用

<MyWebView

style={{width:width-30,marginLeft:15}} width={width-30} source={{html:富文本内容,baseUrl:''}} startInLoadingState={true}/>

©2020 edoou.com   京ICP备16001874号-3