反应本机WebView URL

时间:2017-12-10 23:26:34

标签: android react-native webview

我在从WebView检索当前URL时遇到问题。目前,我正在使用以下方法获取URL

defer db.Close()

最近注意到该网址已弃用!我需要使用source prop来获取URL。但我无法理解。此外,上面的函数被调用两次。有没有办法在onNavigationStateChange() 函数中获取URL?

来源:https://facebook.github.io/react-native/docs/webview.html

由于

1 个答案:

答案 0 :(得分:3)

您可以使用onNavigationStateChange。在导航状态更改上,更新state。并在需要时使用url中的state

代码: -

import React, { Component } from 'react';
import { Text, View, WebView } from 'react-native';

const initialUrl = 'https://github.com';
let url = '';

export default class App extends Component {

  state = {
    url: initialUrl,
  };

  onNavigationStateChange = navState => {
    if (url!==navState.url) { 
      url = navState.url;
      alert(url);
      this.setState({
        url: url
      })
    }
  };

  render() {
    const { url } = this.state;
    return (
      <View style={{paddingTop: 24, flex: 1}}>
        <Text style={{backgroundColor: 'black', color: 'white'}}>{ url }</Text>
        <WebView
        style={{ flex: 1}}
          source={{
            uri: initialUrl,
          }}
          onNavigationStateChange={this.onNavigationStateChange}
          startInLoadingState
          scalesPageToFit
          javaScriptEnabled
        />
      </View>
    );
  }
}

小吃https://snack.expo.io/SyRNRLj-G

上的实例
相关问题