我正在尝试在某些 React 组件中动态加载图像。我在用着require
而不是简单地传递路径以提高性能。
我想我可以使用内联require
它确实有效。然而,当我试图通过prop
相反,我收到错误。
我究竟做错了什么?
EDIT:事实证明两者都有效,我正在做某事else错误是抛出错误。 (奖金问题仍然适用)
import React from 'react';
// This works
export SomeComponent = () => (
<div>
<img src={require(`../images/my-logo.svg`)} />
</div>
)
// This works too!
export SomeComponent = ({image}) => (
<div>
<img src={require(`../images/${image}`)} />
</div>
)
<SomeComponent image="my-logo.svg" />
奖金问题: 这可以用ES6来完成吗import
与 CommonJsrequire
?
不确定它是否会起作用,但你可以尝试:
class Image extends React.Component {
constructor(props) {
super(props)
this.state = { src: null }
}
componentDidMount() {
this.loadImage(this.props.name)
}
componentDidUpdate(prevProps) {
if(prevProps.name !== this.props.name) {
this.loadImage(this.props.name)
}
}
loadImage(name) {
import(`../images/${name}`)
.then(image => {
console.log(image); // this may be object with image inside...
this.setState({ src: image })
})
}
render() {
return <img src={this.state.src} />
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)