react 写移动端H5页面 引用本地图片 且路径正确,但是图片无法正确展示(会展示成默认图片)

26 篇文章 0 订阅
12 篇文章 0 订阅

经过F12查看元素element,

发现react本地编译由浏览器渲染后,竟然是将<img src="../assets/question@2x.png" style={widht: '20px', height: '20px'} />原封不动的解析成了html标签,因此图片才未能被正确引用

错误的图片如下:

 

Card.js (这边直接在img标签写的相对路径,但是无法正确显示)

import React from 'react'
import styles from './card.less'

export default class extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      //
      isShow: false,
    }
  }

  componentDidMount() {}

  showMore = () => {
    const { isShow } = this.state
    const { currentIndex } = this.props
    const contentWrap = document.getElementsByClassName('contentWrap')[
      currentIndex
    ]

    if (!isShow) {
      contentWrap.style.overflow = 'visible'
      contentWrap.style.webkitLineClamp = 'unset'
    } else {
      contentWrap.style.overflow = 'hidden'
      contentWrap.style.webkitLineClamp = '2'
    }
    this.setState({ isShow: !isShow })
  }

  render() {
    const { title, content } = this.props
    // const img = require('../assets/question@2x.png')

    return (
      <div style={{ padding: '0 2px' }}>
        <div
          className={`${styles['shadow-wrap']}`}
        >
          <div
            style={{
              width: '10%',
            }}
          >
            <img src="../assets/question@2x.png" style={{ width: '20px', height: '20px' }} />
          </div>
          <div
            style={{
              width: '90%',
            }}
          >
            <span
              className={`${styles['title']}`}
            >
              {title}
            </span>
            <span className={`${styles['content-wrap']} contentWrap`}>
              {content}
            </span>

            <p
              className={`${styles['show-more']}`}
              onClick={this.showMore}
            >
              {this.state.isShow ? '收起' : '显示更多'}
            </p>
          </div>
        </div>
      </div>
    )
  }
}

在render增加以下代码:

const img = require('../assets/question@2x.png')

 并且修改img标签的src值为:

<img src={img} style={{ width: '20px', height: '20px' }} />


 

正确的图片如下: 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hzxOnlineOk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值