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}/>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容