【问题标题】:JSX - dynamically rendering local imagesJSX - 动态渲染本地图像
【发布时间】:2020-02-06 05:16:41
【问题描述】:

我正在尝试映射一组对象,渲染本地图像,但痛苦地发现这不能像渲染外部 url 那样完成,图像不会触发。

如果不作弊并以声明方式声明本地图像,则无法找到解决方案 - 从...导入徽标 - 或将图像放在公用文件夹中,这可能会给我带来缓存问题。我已经在数组中尝试了 image: require("") 但它似乎没有响应。

这肯定可以动态完成吗?如果有人知道以下问题的解决方案,那真的会对我有所帮助。

目录.jsx

    this.state = {
        categories: [
            {
                title: "Burgers",
                image: "../../images/Burger_landing.jpeg",
                id: 1
            },
            {
                title: "Sides",
                image: "../../images/Fries_main.jpeg",
                id: 2
            },
            {
                title: "Shakes",
                image: "../../images/Shakes_main.jpeg",
                id: 3
            }
        ]
    };
}

render() {
    return (
        <div className='menu__container-position'>
            {this.state.categories.map(({ title, image, id }) => (
                <DirectoryItem key={id} title={title} image={image} />
            ))}
        </div>
    );
}

DirectoryItem.jsx

const DirectoryItem = ({ title, image }) => {
return (
    <div
        className='menu__container-img'
        style={{ backgroundImage: `${image}` }}
    >
        <h1>{title}</h1>
    </div>
);

};

【问题讨论】:

    标签: reactjs image


    【解决方案1】:

    你应该像下面这样设置图片网址

    backgroundImage: `url(${image})` 
    

    或者

    backgroundImage: "url("+image+")"
    

    如果图像不在公共路径中

     backgroundImage: `url(${require(image)})`
    

    【讨论】:

    • 太棒了,这就是我一直在寻找但找不到的语法。谢谢!
    猜你喜欢
    • 2017-08-17
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 2017-01-04
    • 2018-06-30
    • 2015-10-12
    • 2020-04-04
    • 1970-01-01
    相关资源
    最近更新 更多