【问题标题】:React Native load dynamic content onto webviewReact Native 将动态内容加载到 webview
【发布时间】:2018-08-30 07:00:14
【问题描述】:

目前我正在将我的 android assets 文件夹中的 html 文件加载到 webview 中。

dashboard.html 文件包含一些脚本。 如果它是静态的,它工作正常。

<WebView
  ref={(component) => (this.webview = component)}
  style={{ height: height * 1.3 }}
  javaScriptEnabled={true}
  domStorageEnabled={true}
  source={{uri:'file:///android_asset/graph/pages/dashboard.html'}}
  startInLoadingState={true}
  javaScriptEnabledAndroid={true}
  mixedContentMode={'compatibility'}
/>

但我需要动态更新脚本中的变量。 如何从 react-native 组件访问放置在 assets 文件夹中的脚本。

【问题讨论】:

    标签: react-native webview


    【解决方案1】:

    你可以使用 forceUpdate(); 例如

    <webView source={{html: this.state.html}}></webView>
    
    onTestBtnClicked() {
        const html = '<div>test1</div>';
        this.setState({ html });
        this.forceUpdate();
    }
    

    【讨论】:

      【解决方案2】:

      您无法访问和更新脚本文件,但也许您可以在使用注入的 JavaScript 道具加载 WebView 后运行您的脚本或额外代码

      例子:

      const injectedJs = `
          alert("My custom code will go here!");
      `;
      
      return (
          <WebView
          ref={(component) => (this.webview = component)}
          style={{ height: height * 1.3 }}
          javaScriptEnabled={true}
          domStorageEnabled={true}
          source={{uri:'file:///android_asset/graph/pages/dashboard.html'}}
          startInLoadingState={true}
          javaScriptEnabledAndroid={true}
          mixedContentMode={'compatibility'}
          injectedJavaScript={injectedJs}
          javaScriptEnabledAndroid={true}
          />
      );
      

      【讨论】:

      • 谢谢,但我需要在加载 webview 之前更新脚本。除了将文件放入 assets 文件夹之外,还有其他方法可以将本地文件加载到 webview 中吗?
      • 也许您可以使用injectJavaScript 函数,它允许您在调用脚本的确切时间运行脚本。您可以创建一个类似于 alertMessage = () => { } 的函数,并在 webview 的 onLoadStart 事件上调用上述方法。如果您想对脚本进行更改,我建议您使用提到的两种方式之一注入它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多