ReactNative渲染Html

809 阅读1分钟

ReactNative渲染Html

这里我们使用 react-native-render-html 渲染 html,推荐使用最新版本

  1. 安装
   npm install react-native-render-html --save
  1. 使用
import React from 'react'
import { SafeAreaView, View, Text, useWindowDimensions } from 'react-native'
import RenderHtml from 'react-native-render-html'

const App = () => {
  const { width } = useWindowDimensions()
  const renderersProps = {
    img: {
      enableExperimentalPercentWidth: true
    }
  }

  const source = {
    html: `<p style="font-size: 1.2rem; padding: 0 10px;">
      Lorem ipsum dolor sit amet, consectetur adipiscing
      elit, sed do eiusmod tempor incididunt ut labore et
      dolore magna aliqua. Ut enim ad minim veniam, quis
      nostrud exercitation ullamco laboris nisi ut aliquip
      ex ea commodo consequat. 
    </p>
    <p style="color: purple; padding: 0 10px;">
      Duis aute irure dolor in
      reprehenderit in voluptate velit esse cillum dolore
      eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia
      deserunt mollit anim id est laborum.
    </p>
    <img
      width="1200" height="800"
      style="width: 50%; height: 100px; align-self: center;"
      src="http://placeimg.com/1200/800/animals"
    />
    `
  }
  return (
    <SafeAreaView>
      <View>
        <Text>app</Text>
      </View>
      <RenderHtml contentWidth={width} source={source} renderersProps={renderersProps} />
    </SafeAreaView>
  )
}

export default App

  1. 预览

image.png

原文链接