如何在WebView(react-native-webview)中注入React组件?

Pra*_*pta 5 reactjs react-native react-native-webview

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

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

<WebView
        source={{ html: "<ReactContainer/>" }}
></WebView> 
Run Code Online (Sandbox Code Playgroud)

小智 6

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

import { renderToString } from 'react-dom/server'
import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView source={{ html: renderToString(<ReactContainer />) }}></WebView>;


Run Code Online (Sandbox Code Playgroud)

有关 ReactDOMServer 的更多信息请参见此处


小智 -1

如果想直接加载HTML,可以使用WebView\xe2\x80\x99s源属性中的html属性,如下所示:

\n\n
<WebView\n  originWhitelist={[\'*\']}\n  source={{ html: \'<h1>Hello world</h1>\' }}\n/>\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

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

\n\n

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

\n