React-Native在webview不可见时预加载uri

React-Native pre-load uri while webview not visible

本文关键字:加载 uri webview React-Native      更新时间:2023-09-26

我有一个webview在react如下。

      <WebView
        source={{ uri: this.state.url }}
        style={ this.state.style }
        javaScriptEnabled = { true }
        startInLoadingState = {true}
        onLoad = {this.showPage()}
        onLoadEnd = {this.showPage()}
      />

当我设置this.state.url时,我希望webview立即加载url,然后在加载onLoad或onLoadEnd后调用showPage函数显示webview内容。我似乎不能得到这个工作- webview只加载url时,它是可见的dom。有办法做到这一点吗?

最简单的解决方案是使用WebView的renderLoading属性。如果你需要自定义加载器逻辑,你可以这样做:

class WebScreen extends Component {
  ...
  render() {
    const { isLoading } = this.state;
    return (
      <View style={styles.container}>
        <ReactWebView
          style={styles.webview}
          source={{ uri: url }}
          onLoadStart={::this.onLoadStart}
          onLoadEnd={::this.onLoadEnd}
        />
        {isLoading && (
          <WebViewLoader style={styles.loader} />
        )}
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  loader: {
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    zIndex: 4,
    backgroundColor: 'white'
  }
});