简体   繁体   English

资产中用户文件夹的 Src 图像 - React

[英]Src images of user folder in assets - React

Here I am looking for a way to use images in my react applications from a folder in assets/images, in a dynamic way.在这里,我正在寻找一种在我的 react 应用程序中以动态方式从 assets/images 文件夹中使用图像的方法。

Here is the tree structure of my assets folder.这是我的资产文件夹的树结构。

tree structure of my assets folder我的资产文件夹的树结构

I would like to be able to import and use the image of the right user who is connected (I already get all the data).我希望能够导入和使用已连接的正确用户的图像(我已经获得了所有数据)。

But at the time of displaying it, the image is not found...但是在显示它时,找不到图像...

Here is what I tried:这是我尝试过的:

<img src={require(`../../images/user_logo/${userData.logo_name}`)} alt=""/>

or或者

<img src={`../../images/user_logo/${userData.logo_name}`} alt=""/>

And a few other variations... but nothing.还有一些其他的变化......但没有。

Could it be a syntax problem or a webpack problem?可能是语法问题还是 webpack 问题? Knowing that I use in this component a static image that I import at the beginning and use without any problem later, the problem is not the path.知道我在这个组件中使用了一个 static 图像,我一开始导入并在以后使用没有任何问题,问题不在于路径。

Thanks for your help谢谢你的帮助

Edit:编辑:

My React component:我的反应组件:

import React, {useContext} from 'react';
import { Link } from 'react-router-dom';
import authAPI from "../services/authAPI";
import AuthContext from "../contexts/AuthContext"
import Logo from "../../images/VSLogo.svg";
import { toast } from 'react-toastify';

const Header = ({history}) => {

    const {isAuthenticated, setIsAuthenticated,userData} = useContext(AuthContext)


    const handleLogout = () => {
        authAPI.logout()
        setIsAuthenticated(false)
        toast.success('Vous êtes déconnecté !')
        history.push('/')
    }


    return( 
        <nav>
            <Link to="/"><img src={Logo} className="VSLogo"/></Link>
            <ul>
                <li className="navItem"><Link to="/teams">Equipes</Link></li>
                <li className="navItem"><Link to="/tournaments">Tournois</Link></li>
                <li className="navItem"><Link to="/esport">Esport</Link></li>
            </ul>
            {(!isAuthenticated && (
                <>
                    <Link to="/register" className="signUpBtn">S'inscrire</Link>
                    <Link to="/login" className="connexionBtn">Se connecter</Link>
                </>
            )) || (
                <>
                    <img src={`../../images/user_logo/${userData.logo_name}`} alt=""/>
                    <button onClick={handleLogout} className="connexionBtn">Déconnexion</button>  
                </>
            )}
        </nav>
    )
}

export default Header;

My Webpack config (it's webpack encore)我的 Webpack 配置(它是 webpack 安可)

var Encore = require('@symfony/webpack-encore');

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .splitEntryChunks()

    .enableSingleRuntimeChunk()

    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction())

    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = 3;
    })

    .enableSassLoader()

    .copyFiles({
        from: './assets/images',
        to: 'images/[path][name].[ext]',

        //to: 'images/[path][name].[hash:8].[ext]',
        pattern: /\.(png|jpg|jpeg|svg)$/

    })   

    //.addEntry('admin', './assets/js/admin.js')
;

module.exports = Encore.getWebpackConfig();

I solved my problem by adding.default to the require, obviously it's due to a webpack modification again and to the es module.我通过将.default 添加到 require 来解决我的问题,显然这是由于 webpack 再次修改和 es 模块。

var pathToLogo = require(`../../../public/images/user_logo/${userData.logo_name}`).default;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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