react 寫移動端H5頁面 引用本地圖片 且路徑正確,但是圖片無法正確展示(會展示成默認圖片)

經過F12查看元素element,

發現react本地編譯由瀏覽器渲染後,竟然是將<img src="../assets/[email protected]" 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/[email protected]')

    return (
      <div style={{ padding: '0 2px' }}>
        <div
          className={`${styles['shadow-wrap']}`}
        >
          <div
            style={{
              width: '10%',
            }}
          >
            <img src="../assets/[email protected]" 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/[email protected]')

 並且修改img標籤的src值爲:

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


 

正確的圖片如下: 

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