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

有没有一种方法可以直接将web React组件传递到WebView中?类似这样

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

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

如果你想直接加载HTML,你可以使用WebView的源属性中的html属性,如下图所示。

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

关于react-native-web-view的更多细节,你可以从这里了解到。

https:/blog.logrocket.comthe-complete-guid-to-react-native-webview。

https:/github.comreact-native-communityreact-native-weebviewblobmasterdocsReference.md。

0
投票

您可以使用以下方法将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>;


更多关于ReactDOMServer的信息 此处.

0
投票

不,没有。React.js和React native共享相同的语法,但实际上是不同的框架:它们遵循不同的规则,并以不同的方式构建。在webview内部,没有可利用的react框架或运行时(除非你将React.js导入到Webview中)。<script> 标签)。)

然而,正如其他一些答案所指出的,你可以使用 renderToString() 它在某些情况下可以工作(它只是预编译你的组件,并没有提供你想要的东西)--它更多的是一个黑客而不是一个解决方案。