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

时间:2016-09-05 14:56:01

标签: javascript webview react-native

我有一个webview,如下所示。

      <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只在dom中显示时才加载url。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是使用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'
  }
});