Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

reactjs - Fail to require image when using React 17 version

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...