react-native WebView高度计算

左丘恩
2023-12-01

方法一(postMessage与onMessage)

const BaseScript = `
(function () {
    var height = null;
    function changeHeight() {
      if (document.body.scrollHeight != height) {
        height = document.body.scrollHeight;
        if (window.postMessage) {
          window.postMessage(JSON.stringify({
            type: 'setHeight',
            height: height,
          }))
        }
      }
    }
    setTimeout(changeHeight, 300);
} ())
`;
  onMessage(event) {
    try {
      const action = JSON.parse(event.nativeEvent.data);
      if (action.type === 'setHeight' && action.height > 0) {
        this.setState({ height: action.height });
      }
    } catch (error) {
    
    }
  }
  <WebView
    originWhitelist={['*']}
    injectedJavaScript={BaseScript}
    style={{
      width: '100%',
      height: this.state.height,
    }}
    javaScriptEnabled 
    domStorageEnabled 
    onMessage={this.onMessage.bind(this)}
    source={{ html: html, baseUrl: '' }}
  />

方法二(onNavigationStateChange)

  1. html也许是接口中异步请求来的内容,因此用三元表达式确保html存在再显示,否则会出现高度为空的情况。
const { height= 0, html='' }=this.state

    const lastHtml = `
    <!DOCTYPE html>
      <html>
      <body>
        ${html}
      <script>
        window.οnlοad=function(){
          window.location.hash = 1;
          document.title = document.body.clientHeight;
        }
      </script>
      </body>
      </html>
    `;
 {html ? (
    <View style={{ height }}>
      <WebView
        originWhitelist={['*']}
        style={{
          width: '100%',
        }}
        contentInset={{ top: 0, left: 0 }}
        javaScriptEnabled 
        domStorageEnabled
        scrollEnabled={false}
        onNavigationStateChange={(state) => {
          if (parseInt(state.title, 10)) {
            this.setState({
              height: parseInt(state.title, 10) + 20,
            });
          }
        }}
        source={{ html: lastHtml, baseUrl: '' }}
      />
    </View>
 ) : null}
 类似资料: