使用 require('...') 在 react js 中动态导入图像不再工作
Using require('...') to dynamically import images in react js not working anymore
我有旧项目可以用
<img src={require('./logo.svg')} className="App-logo" alt="logo" />
Bu 我用 create-react-app 创建了一个新项目并且 require('...') 不再有效。好像新版本不支持require,请问如何动态加载图片?
旧项目package.json
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
}
新项目package.json
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.0",
"web-vitals": "^0.2.4"
}
您可以通过以下方式导入图片
import Logo from "./logo.svg";
<img src={Logo} className="App-logo" alt="logo" />
我解决了
requires('...') 现在 returns 一个对象,因此您的图像将使用默认键,如下所示
<img src={require('./logo.svg').default} className="App-logo" alt="logo" />
我不知道为什么要更改。
我有旧项目可以用
<img src={require('./logo.svg')} className="App-logo" alt="logo" />
Bu 我用 create-react-app 创建了一个新项目并且 require('...') 不再有效。好像新版本不支持require,请问如何动态加载图片?
旧项目package.json
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
}
新项目package.json
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.0",
"web-vitals": "^0.2.4"
}
您可以通过以下方式导入图片
import Logo from "./logo.svg";
<img src={Logo} className="App-logo" alt="logo" />
我解决了
requires('...') 现在 returns 一个对象,因此您的图像将使用默认键,如下所示
<img src={require('./logo.svg').default} className="App-logo" alt="logo" />
我不知道为什么要更改。