【问题标题】:How to inject React Component inside WebView (react-native-webview)?如何在 WebView (react-native-webview) 中注入 React 组件?
【发布时间】:2020-05-30 20:23:20
【问题描述】:

有没有办法直接将 Web React 组件传递给 WebView?像这样-

import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView
        source={{ html: "<ReactContainer/>" }}
></WebView> 

【问题讨论】:

    标签: reactjs react-native react-native-webview


    【解决方案1】:

    您可以使用 renderToString() 将 React 组件渲染为其初始 HTML,然后将其显示在您的 WebView 中,如下所示:

    import { renderToString } from 'react-dom/server'
    import ReactContainer from 'somewhere';
    import { WebView } from "react-native-webview";
    
    <WebView source={{ html: renderToString(<ReactContainer />) }}></WebView>;
    
    
    

    更多关于 ReactDOMServer 的信息here

    【讨论】:

    • 谢谢@rémi-doreau,这确实渲染了反应组件..按照您建议的上述方法..如果内部反应组件使用文档对象并附加脚本..这将如何工作?你有什么主意吗 ?由于文档对象不适用于 react-native 应用程序。
    • 是否可以将道具传递给&lt;ReactContainer /&gt;
    【解决方案2】:

    如果要直接加载HTML,可以使用WebView的source属性中的html属性,如下图:

    <WebView
      originWhitelist={['*']}
      source={{ html: '<h1>Hello world</h1>' }}
    />
    

    有关 react-native-web-view 的更多详细信息,您可以从此处了解

    https://blog.logrocket.com/the-complete-guide-to-react-native-webview/

    https://github.com/react-native-community/react-native-webview/blob/master/docs/Reference.md

    【讨论】:

      【解决方案3】:

      不,没有。 React.js 和 React native 共享相同的语法,但实际上是不同的框架:它们遵循不同的规则并以不同的方式构建。 在 webview 中,没有可用的 react 框架或运行时(除非您像网站一样将 React.js 作为&lt;script&gt; 标签导入)。

      但是,正如其他答案所指出的那样,您可以使用renderToString(),它会在某些情况下工作(它只是预编译您的组件,它并不能完全提供您想要的东西) - 它更像是一种技巧而不是解决方案。

      【讨论】:

        猜你喜欢
        • 2020-10-05
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-13
        • 2021-06-03
        • 1970-01-01
        • 2017-10-10
        相关资源
        最近更新 更多