ReactNative 0.28:根据内容高度调整WebView的大小

时间:2016-06-23 18:55:42

标签: webview react-native

我基本上问的问题与this one相同,但对于RN 0.28+。各种答案中提出的解决方案在RN 0.28中似乎不起作用,所以我希望有其他配置或黑客...

有没有办法根据内容的高度调整WebView的大小?我尝试将文档高度注入标题并使用onNavigationStateChange阅读,但它始终返回568(类似于the comments to this gist)。

 return <TouchableHighlight onPress={() => console.log('touched ' + this.props.choice.id)}
                           style={styles.choiceRowWrapper} >
      <View style={styles.choiceWebViewWrapper}>
        <WebView automaticallyAdjustContentInsets={false}
                 javascriptEnabled={true}
                 onNavigationStateChange={(navState) => this._updateWebViewNavState(navState)}
                 scrollEnabled={false}
                 source={{html: WrapHTML(this.props.choice.text)}}
                 style={[styles.choiceWebView, {height: this.state.height}]} />
    </View>
  </TouchableHighlight>
 }
  _updateWebViewNavState = (navState) => {
    console.log(navState);
    if (navState.title) {
      this.setState({ height: parseInt(navState.title) });
    }
  }

function WrapHTML (markup) {
    return `<!DOCTYPE html>
      <html>
        <head>
        </head>
        <body class="content">
          ${markup}
        </body>
        <script>window.location.hash = 1;document.title = document.height;</script>
      </html>`;
  };

我还尝试了WebView文档中的各种内容,例如:

document.scrollHeight.contentSize.height
document.body.height

但所有这些都是未定义的。我得到的最接近的是这样的(来自this iOS SO question):

document.getElementById("content").offsetHeight;

但是对于返回20的短文本内容,以及更长的文本内容(一个完整的句子),它返回40 ......两者都不准确。

我也开始尝试this RN component,但是回购表明它没有被主动维护 - npm上的最新版本不支持RN 0.28,因为他们为单独导入React(而不是从ReactNative导入)。

有没有人使用RN 0.28让WebViews正确调整大小?

1 个答案:

答案 0 :(得分:0)

经过大量的研究和修补,我发现这种方法是将文档标题设置为屏幕高度值的更为复杂的版本。在我的测试中,这适用于Android和iOS,反应原生为0.47。

https://gist.github.com/xyos/dcaa43fa561760b9d6194d78e5fb7721