ReactJS and images in public folder

后端 未结 7 1568
北恋
北恋 2020-11-30 01:15

Im new in ReactJS and I want to import images in a component. These images are inside of the public folder and I do not know how to access the folder from the react componen

相关标签:
7条回答
  • 2020-11-30 01:46

    You should use webpack here to make your life easier. Add below rule in your config:

    const srcPath = path.join(__dirname, '..', 'publicfolder')
    
    const rules = []
    
    const includePaths = [
      srcPath
    ]
        // handle images
        rules.push({
          test: /\.(png|gif|jpe?g|svg|ico)$/,
          include: includePaths,
          use: [{
            loader: 'file-loader',
            options: {
              name: 'images/[name]-[hash].[ext]'
            }
          }
    

    After this, you can simply import the images into your react components:

    import myImage from 'publicfolder/images/Image1.png'
    

    Use myImage like below:

    <div><img src={myImage}/></div>
    

    or if the image is imported into local state of component

    <div><img src={this.state.myImage}/></div> 
    
    0 讨论(0)
提交回复
热议问题