【问题标题】:Getting and Passing variables inside React Native from Webview从 Webview 获取和传递 React Native 中的变量
【发布时间】:2020-07-17 14:05:28
【问题描述】:

我在我的项目 React Native 中使用 [react-native-webview][1]。我的 webview 有一个 javascript 数组,我需要获取这个数组并在一个菜单中显示值,就像这个幻灯片菜单: https://raw.githubusercontent.com/instea/react-native-popup-menu/master/android.demo.gif

代码:

function WebViewPage(){
    const html = `
           <html>
           <body>
            <div id="reportContainer">here apear the content..</div>
            <script>
                  var reportContainer = document.getElementById('reportContainer');
                   var pages = [];
              reportContainer.getPages().then(function (reportPages) {
              //HERE RETURN A LIST FROM PAGES FROM MY REPORT..
              pages = reportPages;
              });
          </script>
          </body> 
           </html>
    `
   return(
    <Page>
     <WebView source={{html:html}} />
   </Page>
  );
}

export default WebViewPage;

基本上,我需要获取 pages 数组并在我的 Header 中放置 Menu。我正在考虑使用钩子,但我不知道如何获得这个数组,有什么想法吗?谢谢你。 [1]:https://github.com/react-native-community/react-native-webview

【问题讨论】:

  • 你想做什么?为什么不直接导入你的脚本?
  • @BloodyMonkey 在我的网络视图中显示图表。这个图表有很多页。我想制作一个带有页面的菜单,当用户选择菜单上的页面时,我必须再次将页面发送到 webview 以在 webview 上打开特定图表。

标签: reactjs react-native webview


【解决方案1】:

您可以在webview 组件上使用onMessage 回调函数。

function WebViewPage(){
    const html = `
           <html>
           <body>
           <div id="reportContainer">here apear the content..</div>
           <script>
              var reportContainer = document.getElementById('reportContainer');
              var pages = [];
              reportContainer.getPages().then(function (reportPages) {
                 //HERE RETURN A LIST FROM PAGES FROM MY REPORT..
                 pages = reportPages;
                 window.postMessage(pages);
              });
           </script>
           </body> 
           </html>
    `
   const onMessage(data) { 
      console.log(data);
   }

   return(
    <Page>
     <WebView onMessage={onMessage} source={{html:html}} />
   </Page>
  );
}

export default WebViewPage;

【讨论】:

  • 嗨,谢谢!!,我在消息上搜索这个方法,正确的是:onMessage={(event) =&gt; onMessage(event.nativeEvent.data)}。并且通过是:window.ReactNativeWebView.postMessage("parameter from webview"); 现在我要得到:)。如果我现在想将某些内容传递给 webview,它是如何工作的?
  • 这是一个很好的例子,有一个解释。 undefinednull.com/2015/12/27/…
  • 谢谢我的朋友
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多