在 React Native 中渲染 HTML [英] Render HTML in React Native
问题描述
在我的 React Native 应用程序中,我正在提取具有原始 HTML 元素的 JSON 数据,如下所示:<p>这是一些文本.让’我们弄清楚...</p>
In my React Native app, I am pulling in JSON data that has raw HTML elements like this: <p>This is some text. Let’s figure out...</p>
我已将数据添加到我的应用中的视图中,如下所示:
I've added the data to a view in my app like this:
问题是 HTML 是原始的,它不像在浏览器中那样呈现.有没有办法让我的 JSON 数据在浏览器中的应用视图中看起来像它一样?
The problem is that the HTML comes out raw, it does not render like it would in a browser. Is there a way to get my JSON data to look like it would in a browser, inside my app view?
推荐答案
Edit Jan 2021:React Native 文档目前推荐 React Native WebView:
Edit Jan 2021: The React Native docs currently recommend React Native WebView:
<WebView
originWhitelist={['*']}
source={{ html: '<p>Here I am</p>' }}
/>
https://github.com/react-native-webview/react-native-webview
编辑 2017 年 3 月:html
道具已被弃用.使用 source
代替:
Edit March 2017: the html
prop has been deprecated. Use source
instead:
<WebView source={{html: '<p>Here I am</p>'}} />
https://facebook.github.io/react-native/docs/webview.html#html
感谢贾斯汀指出这一点.
2017 年 2 月不久前接受了 PR,因此要在 React Native 中渲染 HTML,只需:
Edit Feb 2017: the PR was accepted a while back, so to render HTML in React Native, simply:
<WebView html={'<p>Here I am</p>'} />
原答案:
Original Answer:
我认为目前这是不可能的.您看到的行为是意料之中的,因为 Text 组件只输出......好吧,文本.您需要另一个输出 HTML 的组件 - 这就是 WebView.
I don't think this is currently possible. The behavior you're seeing is expected, since the Text component only outputs... well, text. You need another component that outputs HTML - and that's the WebView.
不幸的是,现在无法直接在此组件上设置 HTML:
Unfortunately right now there's no way of just directly setting the HTML on this component:
https://github.com/facebook/react-native/issues/506
但是我刚刚创建了 这个 PR,它实现了一个基本版本这个功能,所以希望它很快就会以某种形式登陆.
However I've just created this PR which implements a basic version of this feature so hopefully it'll land in some form soonish.
这篇关于在 React Native 中渲染 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!