ReactNative H5 页面显示 react-native-webview 高度自适应

本文介绍了如何在ReactNative应用中使用WebView并实现高度自适应。通过引入react-native-webview包,结合简单示例和高度自适应策略,确保H5页面在ReactNative环境中能正确显示并自动调整高度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装包

react-native-webview

简单示例

import React from 'react'
import WebView from 'react-native-webview'

class Component extends React.Component {
    createHtml() {
        return `
        <div id="canvas" style=""></div>
        <script>
            window.onload = function () {
            }
        </script>
        `
}

    render() {
        return (
            <WebView
                source={{ html: this.createHtml() }}
            />
        );
    }
}

export default Component;

高度自适应

import React from 'react'
import WebView from 'react-native-webview'

interface Props {
    html: string
}

export default class IEWebView extends React.Component<Props> {
    state = {
        webHeight: 0
    }

    constructor(props) {
        super(props);
    }

    createHtml(html) {
        return `
        <body style="margin: 0px">
            <div id="__container__">
                ${html}
                <div></div>
            </div>
            <script>
                var oldonload = window.onload;//得到上一个onload事件的函数

                window.onload = function () {
                    if (typeof oldonload == 'function') {
                        oldonload();
                    } 

                    setTimeout(()=>{
                        // 向 WebView 发送消息
                        let webHeight = document.getElementById("__container__").clientHeight;
                        window.ReactNativeWebView.postMessage(webHeight);
                    }, 1)
                }
            </script>
        <body>
        `
    }

    onMessage = (msg) => {
        console.log("--------------------------")
        console.log(msg.nativeEvent)

        if (msg.nativeEvent.data !== undefined && msg.nativeEvent.data !== null) {
            let height = parseInt(msg.nativeEvent.data);
            if (isNaN(height)) {
                height = 0;
            }
            this.setState({
                webHeight: height
            });
        }
    }

    render() {
        console.log(this.createHtml(this.props.html));
        return (
            <WebView
                style={{ width: '100%', height: this.state.webHeight }}
                javaScriptEnabled={true}
                source={{ html: this.createHtml(this.props.html) }}
                onMessage={this.onMessage}
                scalesPageToFit={false}
            />
        );
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值