[Taro入门:5] 加载图片资源

2,337 阅读2分钟

这是我参与更文挑战的第3天,活动详情查看:更文挑战

图片是页面当中最常用的信息展示方式之一。 图片资源可以通过本地引入或远程加载。

一、 远程加载

远程加载是指提供图片的url,页面加载时通过http请求下载图片并显示到页面上。

在Taro中将Image标签的src属性设置成图片的url即可:

// src\pages\liyue\index.js
import { Component } from 'react'
import { View, Text,Image,Button } from '@tarojs/components'
import Taro from '@tarojs/taro'
export default class Index extends Component {
  render () {
    return (
      <View className='index'>
        <View>璃月</View>
        <View>位于提瓦特大陆东方的富饶港湾。</View>
        <Text>
            傲然矗立的山麓与石林、广袤的平原与生机勃勃的河滩共同构成了璃月的丰富地貌,在四季分明的气候下焕发出多彩的风华。
            山石奇景间,又埋藏了多少岩之魔神的古老馈赠等待着人们发掘呢?
        </Text>
        <Image src='https://uploadstatic.mihoyo.com/contentweb/20200319/2020031921552395638.jpg'
        mode='center'
        />
      </View>
    )
  }
}

效果:

image.png

二、 import/require 加载本地图片

在Taro中可以通过import或require的方式引入本地图片:

// src\pages\mengde\index.js
import { Component } from 'react'
import { View, Text,Image } from '@tarojs/components'
import Logo from '../../image/logo.png'
export default class Index extends Component {
  render () {
    return (
      <View className='index'>
        <View>蒙德</View>
        <View>位于提瓦特大陆东北部的自由城邦。</View>
        <Text>
          群山和广袤的平原间,自由之风携着蒲公英的气息吹拂过果酒湖,
          为坐落于湖心岛上的蒙德城送去风神巴巴托斯的祝福与恩泽。
        </Text>
        // import方式
        <Image style="width: 100px;height: 100px;" src={Logo} />
        // require方式
        <Image style="width: 100px;height: 100px;" src={require('../../image/logo.png')} />
      </View>
    )
  }
}

通过这种方式,打包时图片会打包到dist目录中,由于小程序对打包体积有限制,不建议将较多或尺寸较大的图片通过这种本地方式引入。

三、 样式中的本地图片自动转化为Base 64

在小程序的样式中,默认不能直接引用本地资源,只能通过网络地址、Base64 的方式来进行资源引用,为了方便开发,Taro 提供了直接在样式文件中引用本地资源的方式,其原理是通过 PostCSS 的 postcss-url 插件将样式中本地资源引用转换成 Base64 格式,从而能正常加载。

Taro 默认会对 1kb 大小以下的资源进行转换,如果需要修改配置,可以在 config/index.js 中进行修改,配置位于 mini.postcss

// config\index.js
const config ={
    // 省略其他配置项
    mini: {
    postcss: {
      url: {
        enable: true,
        config: {
          limit: 1024 // 设定转换尺寸上限
        }
      }
  },
}

demo:

import { Component } from 'react'
import { View, Image } from '@tarojs/components'

export default class Index extends Component {
  render () {
    return (
      <View class="img-bg"></View>
    )
  }
}
.img-bg {
    width: 100px;
    height: 100px;
    background-size: contain;
    background-image: url('../../image/iconfont-zan.svg');
}

效果: image.png

编译后的index.wxss

image.png

需要注意,这种方式只能在样式中使用,在Image标签的src属性上使用是无效的。