在React Native中呈现HTML

时间:2015-03-29 21:21:29

标签: react-native

在我的React Native应用程序中,我将提取具有如下原始HTML元素的JSON数据:<p>This is some text. Let&#8217;s figure out...</p>

我已将数据添加到我的应用中的视图中,如下所示:

<Text>{this.props.content}</Text>

问题在于HTML是原始的,它不像在浏览器中那样渲染。有没有办法让我的JSON数据看起来像在浏览器中,在我的应用程序视图中?

6 个答案:

答案 0 :(得分:42)

2017年3月编辑:html道具已被弃用。请改用source

<WebView source={{html: '<p>Here I am</p>'}} />

https://facebook.github.io/react-native/docs/webview.html#html

感谢Justin指出这一点。


编辑2017年2月:PR被接受了一段时间,所以要在React Native中呈现HTML,只需:

<WebView html={'<p>Here I am</p>'} />

原始答案:

我认为目前无法做到这一点。您期待看到的行为是预期的,因为Text组件只输出......好吧,文本。您需要另一个输出HTML的组件 - 这是WebView

不幸的是,目前还没有办法直接在这个组件上设置HTML:

https://github.com/facebook/react-native/issues/506

但是,我刚刚创建了this PR,它实现了此功能的基本版本,所以希望它很快会以某种形式着陆。

答案 1 :(得分:10)

我找到了这个组件。 https://github.com/jsdf/react-native-htmlview

此组件获取HTML内容并将其呈现为本机视图,具有可自定义的样式和链接处理等。

答案 2 :(得分:5)

一个iOS / Android纯javascript react-native组件,可将您的HTML呈现为100%本机视图。它具有极高的可定制性和易用性,旨在能够呈现您扔给它的任何东西。

react-native-render-html

使用上述库可提高您的应用性能水平并易于使用。

安装

npm install react-native-render-html --save or yarn add react-native-render-html

基本用法

import React, { Component } from 'react';
import { ScrollView, Dimensions } from 'react-native';
import HTML from 'react-native-render-html';

const htmlContent = `
    <h1>This HTML snippet is now rendered with native components !</h1>
    <h2>Enjoy a webview-free and blazing fast application</h2>
    <img src="https://i.imgur.com/dHLmxfO.jpg?2" />
    <em style="textAlign: center;">Look at how happy this native cat is</em>
`;

export default class Demo extends Component {
    render () {
        return (
            <ScrollView style={{ flex: 1 }}>
                <HTML html={htmlContent} imagesMaxWidth={Dimensions.get('window').width} />
            </ScrollView>
        );
    }
}

PROPS

您还可以使用以下链接参考来使用不同类型的道具(请参阅上面的链接)进行设计和自定义。

Customizable render html

答案 3 :(得分:1)

React Native已更新WebView组件以允许直接html呈现。这是一个适合我的例子

var htmlCode = "<b>I am rendered in a <i>WebView</i></b>";

<WebView
  ref={'webview'}
  automaticallyAdjustContentInsets={false}
  style={styles.webView}
  html={htmlCode} />

答案 4 :(得分:0)

 <WebView ref={'webview'} automaticallyAdjustContentInsets={false} source={require('../Assets/aboutus.html')} />

这对我有用:)我有html文本aboutus文件。

答案 5 :(得分:0)

我仅使用Js函数 替换

<Text>{item.excerpt.rendered.replace(/<\/?[^>]+(>|$)/g, "")}</Text>
相关问题