【问题标题】:react-native-webview Navigate to a list of URLs?react-native-webview 导航到 URL 列表?
【发布时间】:2021-08-31 18:44:21
【问题描述】:

正如问题标题所说,我正在尝试使用 React Natives WebView 组件导航到 url 列表。以下是我尝试实现此目的的方法:

export default function App() {
  
  const webViewScript = `
    let urls = ["http://example1.com", "http://example2.com", "http://example3.com"];
    urls.forEach((url) => {
      window.location = url;
      window.ReactNativeWebView.postMessage(document.documentElement.innerHTML);
    });

    true; // note: this is required, or you'll sometimes get silent failures
  `;

  return (
    <WebView
      source={{ uri: navUri }}
      onMessage={(event) => {
        // do something with `event.nativeEvent.data`
        alert(event.nativeEvent.data);
      }}
      injectedJavaScript={webViewScript}
    />
  );
}

但是,注入的 javascript 中的 foreach 循环不会阻塞,因此 example3.com 是唯一实际加载的 url。我考虑在 localStorage 中保留一个计数器变量并使用它来索引数组,在每次页面加载后递增,然后重定向到下一个 URL(因为局部变量会在页面更改时失去其状态)。但我觉得可能有更好的方法来完成我想要实现的目标,因此我正在与 SO 上的其他人联系以征求您的宝贵意见。

【问题讨论】:

    标签: javascript react-native react-native-webview


    【解决方案1】:

    如果您的目标是导航到 url 列表,那么我认为您的方法可能会使它有点复杂。

    webview 具有回调属性“onLoadEnd”,用于在网站加载时触发下一次导航。

    另外你不需要在 localStorage 中存储变量,reacts useState 非常适合。

    Demo

    const urls = [
      'https://github.com/react-native-webview/react-native-webview',
      'https://stackoverflow.com/',
      'https://expo.dev/',
    ];
    
    export default function App() {
      const [activeIndex, setActiveIndex] = useState(0);
    
      return (
        <WebView
          style={styles.container}
          source={{ uri: urls[activeIndex] }}
          onLoadEnd={() => {
            if (activeIndex + 1 === urls.length) return;
            setActiveIndex(activeIndex + 1);
          }}
        />
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        marginTop: Constants.statusBarHeight,
      },
    });
    

    【讨论】:

    • 感谢您的回复,继续将其标记为答案。我有一种直观的感觉,有一种更好的方法可以做到这一点,我很确定这是你提供的方法。 react-native 是全新的,所以这对我很有帮助。我很感激。
    • 我很乐意提供帮助!
    猜你喜欢
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    相关资源
    最近更新 更多