经过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' }} />