用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--------------------------

 

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