根据内容设置包含 WebView 的 View 的高度

时间:2021-07-22 09:18:25

标签: react-native webview

我想将我的 WebView 设置为与我要显示的内容相同的高度,仅此而已。

我有一个包含在视图中的 WebView:

<View style={height: height}>
  <WebView
    ...
    onMessage={event => console.log(event.native.data)} // this returns height of element in px
  />

在 WebView 内部,它只是一个 div。我正在使用 postMessage 将 WebView 上 div 的高度发送到我的 React Native 应用程序。我如何转换该数字(在 px 中)以在 React Native 中设置样式?

我曾尝试使用 PixelRatio.getPixelSizeForLayoutSize 但它不正确。提前致谢!

1 个答案:

答案 0 :(得分:1)

您可以使用react-native-autoheight-webview,它会根据内容设置高度。

import AutoHeightWebView from 'react-native-autoheight-webview'

import { Dimensions } from 'react-native'

<AutoHeightWebView
    style={{ width: Dimensions.get('window').width - 15, marginTop: 35 }}
    customStyle={`
      * {
        font-family: 'Times New Roman';
      }
      p {
        font-size: 16px;
      }
    `}
    onSizeUpdated={size => console.log(size.height)}
    source={{ html: `<p style="font-weight: 400;font-style: normal;font-size: 21px;line-height: 1.58;letter-spacing: -.003em;">Tags are great for describing the essence of your story in a single word or phrase, but stories are rarely about a single thing. <span style="background-color: transparent !important;background-image: linear-gradient(to bottom, rgba(146, 249, 190, 1), rgba(146, 249, 190, 1));">If I pen a story about moving across the country to start a new job in a car with my husband, two cats, a dog, and a tarantula, I wouldn’t only tag the piece with “moving”. I’d also use the tags “pets”, “marriage”, “career change”, and “travel tips”.</span></p>` }}
    scalesPageToFit={true}
    viewportContent={'width=device-width, user-scalable=no'}
    /*
    other react-native-webview props
    */
  />
相关问题