react-native中使用webview来渲染富文本,修改样式,自适应高度

我们知道,在vue中,我们可以很轻松的去渲染富文本内容。包括在小程序中也有对应的组件可以直接使用。

那么,在react-native中如何渲染富文本呢?

答案是: Webview

废话不多说,直接上代码。


import React, { Component } from 'react';
import {
  View,
  Image,
  Text,
  StyleSheet,
  Dimensions,
  TouchableOpacity,
} from 'react-native';

import { WebView } from 'react-native-webview';

export default class ArticleDetailPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: '',
      content: '',
      webViewHeight: 0 // webview高度,动态计算得出
    };
  }

  componentDidMount() {
    const { id = '' } = this.props.route.params
    this.fetchDetail(id)
  }

  fetchDetail(id) {
    getArticleDetail({ articleId: Number(id) }).then(res => {
      this.setState({
        title: res.data.title,
        content: res.data.content
      })
    }).catch(err => {
      console.log(err)
    })
  }

  // 根据内容动态计算 webview的高度
  onWebViewMessage = (e) => {
    // console.log('----------e', e)
    this.setState({ webViewHeight: Number(e.nativeEvent.data) });
  }

  render() {
    const { title, content} = this.state

    const BaseScript = `
    (function () {
        var height = null;
        function changeHeight() {
          if (document.body.scrollHeight != height) {
            height = document.body.scrollHeight;
            if (window.postMessage) {
              window.ReactNativeWebView.postMessage(height)
            }
          }
        }
        setTimeout(changeHeight, 300);
    } ())
    `;

    const htmlContent = `
      <html>
        <head>
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <style>
            p{
              text-indent: 2em;
            }
          </style>
        </head>
        <body>
        ${content}
        </body>
      </html>
    `
    return (
      <ScrollView style={{ flexDirection: 'column', flex: 1, backgroundColor: '#ffffff' }}>
        <Text style={styles.articleTitle}>{title}</Text>
        <View style={[styles.articleContent, { height: this.state.webViewHeight, marginTop: 10, paddingHorizontal: 5 }]}>
          <WebView
            source={{ html: htmlContent, baseUrl: '' }}
            injectedJavaScript={BaseScript}
            automaticallyAdjustContentInsets={false}
            javaScriptEnabled={true}
            decelerationRate="normal"
            startInLoadingState={true}
            onMessage={this.onWebViewMessage}
          />
        </View>
      </ScrollView>
    );
  }
}

其中,接口返回的数据为:

{
content: "<p><span style="font-size: 14pt;">&nbsp; &nbsp; 努力,从不会白费。</span></p>↵<p><span style="font-size: 14pt;">&nbsp; &nbsp; =现在回头看,一切努力是不算白费的。</span></p>↵<p><span style="font-size: 14pt;">&nbsp; &nbsp; 我是其他内容。</span></p>↵<p>&nbsp;</p>↵<p></p>",
title:'我是文字标题'
}

我们可以在htmlContent中写css样式来控制富文本内容。

大家也可以参考这篇文章: https://blog.csdn.net/shizhihua11/article/details/88932742

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值