Javascript 如何使用CreateReact应用程序在React中导入图像(SVG或PNG)

Javascript 如何使用CreateReact应用程序在React中导入图像(SVG或PNG),javascript,reactjs,typescript,create-react-app,Javascript,Reactjs,Typescript,Create React App,例如,我有一个图标元素的 <i style={{ backgroundImage: `url(${'./images/names/Mike.svg'}` }}/> 但还是不行,除非我硬编码名字 backgroundImage: `url(${require(`assets/images/names/Mike.svg`)})` 这在我的例子中是不可行的。这里有三种方法可以将图像(SVG和PNG)导入React项目。您可以将任一文件类型与所有三个选项一起使用 导入图像并在src属性中

例如,我有一个图标元素的

<i style={{ backgroundImage: `url(${'./images/names/Mike.svg'}` }}/>
但还是不行,除非我硬编码名字

backgroundImage: `url(${require(`assets/images/names/Mike.svg`)})`

这在我的例子中是不可行的。

这里有三种方法可以将图像(SVG和PNG)导入React项目。您可以将任一文件类型与所有三个选项一起使用

  • 导入图像并在src属性中使用它
  • 导入图像并在样式属性中使用它
  • 动态插入到require函数中
  • 见以下示例:

    import React from 'react';
    import backgroundImg from '../assets/images/background.png';
    import logoImg from '../assets/images/logo.svg';
    
    const Test = props => {
    
         const imageLink = 'another.png'
         // const imageLink = props.image
         // You can loop this component in it's parent for multiple images.
    
         return (
             <div>
                  <img src={logoImg} style={{ width: '200px', height: '45px' }} />
                  <div style={{ width: '100%', height: '100%', backgroundImage: `url(${backgroundImg})`, backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundSize: 'cover', position: 'fixed'}} />
                  <img width={900} height={500} alt="test img"  src={require(`../assets/images/${imageLink}`)}/>
             </div>
         )
    }
    
    export default Test
    
    从“React”导入React;
    从“../assets/images/background.png”导入backgroundImg;
    从“../assets/images/logo.svg”导入logoImg;
    常量测试=道具=>{
    const imageLink='other.png'
    //const imageLink=props.image
    //可以在多个图像的父组件中循环此组件。
    返回(
    )
    }
    导出默认测试
    
    hi,标签不用于iconWhat如果我需要导入300张图像?我在上面添加了第三个选项,可以满足您的需要。
    import React from 'react';
    import backgroundImg from '../assets/images/background.png';
    import logoImg from '../assets/images/logo.svg';
    
    const Test = props => {
    
         const imageLink = 'another.png'
         // const imageLink = props.image
         // You can loop this component in it's parent for multiple images.
    
         return (
             <div>
                  <img src={logoImg} style={{ width: '200px', height: '45px' }} />
                  <div style={{ width: '100%', height: '100%', backgroundImage: `url(${backgroundImg})`, backgroundRepeat: 'no-repeat', backgroundPosition: 'center', backgroundSize: 'cover', position: 'fixed'}} />
                  <img width={900} height={500} alt="test img"  src={require(`../assets/images/${imageLink}`)}/>
             </div>
         )
    }
    
    export default Test