React Native 动态 webview 高度

IT技术 javascript webview reactjs react-native
2021-05-03 20:45:53

我有 WebView 内容,它根据内容的数量改变它的高度。于是我找到了一种方法,如何通过 onNavigationStateChange 的 document.title 属性来获取内容的高度。看起来像这样:

let html = '<!DOCTYPE html><html><body><script>document.title = document.height;</script></body></html>';

和 onNavigationStateChange

onNavigationStateChange(navState) {
  this.setState({
    height: navState.title
  });
  console.log("DATA");
  console.log(this.state.height)
}

在实际的 WebView 渲染中,我这样做:

<WebView style={this._setWebviewHeight()}
           automaticallyAdjustContentInsets={false}
           scrollEnabled={false}
           onNavigationStateChange={this.onNavigationStateChange.bind(this)}
           html={html}>
</WebView>

在哪里:

_setWebviewHeight() {
 return {
  height: this.state.height,
  padding: 20,
 }
}

在这种情况下,我收到错误,并且无法通过状态获取内容的高度。那我该怎么办?

解决方案的想法来自这里:React native: Is it possible to have the height of a html content in a webview?

2个回答

我在 RN 第三方库之一的实现中找到了解决方案。这是它的链接:https : //github.com/danrigsby/react-native-web-container/blob/master/index.js

有了这种方法,一切都很好。

试试这个库:https : //github.com/iou90/react-native-autoheight-webview 它适用于 iOS 和 Android