首页 > 解决方案 > 从 Webview 获取和传递 React Native 中的变量

问题描述

我在我的项目 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;

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

标签: reactjsreact-nativewebview

解决方案


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

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;

推荐阅读