I am new to React and now learning the latest version with create-react-app. I met one issue hope someone could help.
export default class LeftNav extends React.Component {
show() {
let test = '../../assets/images/test.png';
let src = require('../../assets/images/test.png'); // test.png can be successfully loaded.
// below 2 lines both throw compilation error saying it could not resolve test.png, but why
// directly require works
// let src = require(test);
// let src = require(`${test}`);
return (
<div className="container">
<img src={src.default} alt=""/>
</div>
)
}
render() {
return <div>{this.show()}</div>
}
}
I have many images so it is not reasonable to import them one by one in the jsx file so that's why i am testing to dynamically include those assets. But the result shows we are not able to use variable to store asset path inside require(variable). Does someone know why this happens? is this a React bug? The react version i use is 17.0.1. BTW, require() now returns an object so i use .src to get the real asset. thank you
question from:
https://stackoverflow.com/questions/65951374/fail-to-require-image-when-using-react-17-version 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…