【问题标题】:React 17.0.1 - Importing Component with Dynamic PathReact 17.0.1 - 使用动态路径导入组件
【发布时间】:2021-05-03 07:57:15
【问题描述】:

我正在尝试学习如何使用 this guide 使用“useState”钩子,但我似乎无法导入具有动态路径的图像,因此当我单击按钮时,元素会获取新路径并更改图像.

以下是指南导入图像的方式:

...
function App() {
  const [firstDieResult, setFirstDieResult] = useState(1);
  const [secondDieResult, setSecondDieResult] = useState(6);
  
  const firstDieImage = require(`./assets/${firstDieResult}.png`);
  const secondDieImage = require(`./assets/${secondDieResult}.png`);
...

但是,当我尝试以这种方式导入图像时,它不会导入它们。我是这样导入它们的:

import React, {useState} from 'react';
import './App.css';
import firstDieImage from './assets/1.png'
import secondDieImage from './assets/2.png'

function App() {
...

但是当我以这种方式导入它们时,我无法导入动态路径(如import firstDieImage from './assets/${firstDieResult}.png')。

如何以这种方式导入图像?
感谢您的宝贵时间。

完整代码供参考:

import React, {useState} from 'react';
import './App.css';
import firstDieImage from './assets/1.png'
import secondDieImage from './assets/2.png'

function App() {

  const [firstDieResult, setFirstDieResult] = useState(1)
  const [secondDieResult, setSecondDieResult] = useState(6)
  console.log(secondDieResult)
  
  //Commented out parts work in the guide, but not for me
  //const firstDieImage = require('./assets/1.png')
  //const secondDieImage = require('./assets/2.png')
  //const firstDieImage = require('./assets/${firstDieResult}.png')
  //const secondDieImage = require('./assets/${secondDieResult}.png');

  return (
    <div className="App">
      <header className="App-header">
        <div style={{ display: 'flex', margin: 20 }}>
          <img src={firstDieImage} className="die" alt="Die one" />
          <img src={secondDieImage} className="die" alt="Die two" />
        </div>
        <span>firstDieResult + secondDieResult</span>
        <button className="button">Roll</button>
      </header>
    </div>
  );
}

export default App;

【问题讨论】:

    标签: reactjs image dynamic import path


    【解决方案1】:

    您的代码有错误。

    const firstDieImage = require('./assets/${firstDieResult}.png')
    

    您应该使用反引号字符 (`) 而不是单引号 (')。如果您使用 create-react-app 模块创建项目,请像这样更新代码:

    const firstDieImage = require(`./assets/${firstDieResult}.png`).default
    

    您可以从此git repo 找到工作代码。

    【讨论】:

    • 反引号和单引号的作用相同,至少在这种情况下是这样。
    • 您检查了代码框链接吗?请检查代码。您会发现代码正在使用反引号。
    • 我做到了,但链接中的代码在我的 VS Code 上不起作用。知道什么可能导致这种行为吗?
    • @Krokzter 更新了答案。此代码适用于您的 VS Code。
    • 是的,确实有效,非常感谢您抽出宝贵时间。对于将来遇到此问题的任何人要注意的一件事,截至此时 React 不适用于 Typescript 4 或更高版本,因此请使用“npm remove typescript”将其卸载,然后使用“npm i typescript”再次安装。它将安装 Typescript 3.9.7。
    猜你喜欢
    • 2019-04-03
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多