简体   繁体   中英

React 17.0.1 - Importing Component with Dynamic Path

I am trying to learn how to use "useState" hooks using this guide but I can't seem to import images with a dynamic path, so that when I click a button the element gets a new path and changes the image.

Here is how the guide is importing images:

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

However, when I try to import images this way it wont import them. I am importing them as such:

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

function App() {
...

But when I import them this way, I can't import a dynamic path (like import firstDieImage from './assets/${firstDieResult}.png' ).

How do I go about importing images this way?
Thank you for your time.

Whole code for reference:

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;

Your code has a mistake.

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

You should use backtick character (`) instead of a single quote ('). And if you create project using create-react-app module, update the code like this:

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

You can find working code from this git repo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM