用Taro写一个微信小程序——渲染 HTML

🌲 在taro小程序里面渲染一段html代码,具体可查看文档https://docs.taro.zone/docs/html

一、渲染 HTML

文档推荐使用 dangerouslySetInnerHTML 方法来渲染HTML。

1、用法

用法很简单,如下:

<View className="taro_html k_html" dangerouslySetInnerHTML={{ __html: html }}></View>

 

2、自定义HTML样式

Taro 提供两种内置样式我们可以直接引入生效,引入后只需将 HTML 容器的 CSS 类设置为 .taro_html就可以了(如上面的例子)

import '@tarojs/taro/html.css'; // 引入taro内置样式文件

我们自己也可以添加类名,对默认样式进行修改(如上面的k_html)

.k_html {
  .img {
    width: 100%;
  }
  .p {
    line-height: 48px;
    text-align: justify;
    font-size: 32px;
    color: $color-black3a;
  }
}

 

3、高级选项transformElement

image的默认mode是scaleToFill,在图片宽高不确认的情况下样式上很难调节(如下图),所以我们要更改image的mode。

 

使用transformElement更改image的mode为widthFix

Taro.options.html.transformElement = (el) => {
  if (el.nodeName === 'image') {
    el.setAttribute('mode', 'widthFix')
  }
  return el;
};

 

二、遇到的问题

在使用transformElement更改image的mode时,我开始将这个方法放到了生命周期函数中执行,这会导致第一次进入页面的时候mode没有更改。

完整示例

import { Component } from 'react'
import Taro from "@tarojs/taro";
import { View } from '@tarojs/components'

Taro.options.html.transformElement = (el) => {
  if (el.nodeName === 'image') {
    el.setAttribute('mode', 'widthFix')
  }
  return el
}

export default class Index extends Component {
  render () {
    return (
      <View className='home' dangerouslySetInnerHTML={{ __html: '<img src="https://a/b/c" />' }} />
    )
  }
}

 

End--------------------------

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章