在React中为div添加背景图像?

问题描述 投票:0回答:1
render(){
        const { classes } = this.props;
        const { imageDescription } = this.props.imgDesc;
        const { currentIndex } = this.state;

        var fullPath = `../images/Large/${(imageDescription[currentIndex]).imagePath}.jpg`;
        console.log("Fullpath: "+fullPath);

        return (
            <div style={{ 'background-image': "url(" + require(fullPath) + ")" }}>
            </div>

我有一个组件返回带有背景图像的div,但是当它启动时它显示错误,找不到模块'../ images / Large / homeTecno.jpg'。但是,当我使用console.log语句的输出更改require中的变量fullPath时,它有效吗?

javascript reactjs material-ui
1个回答
2
投票

这是因为require仅用于导入javascript实体(类,对象,函数,...)而不是图像。设置背景图像时,只需要一个字符串,而不是一个对象。这就是你的第二个解决方案的原因。

请注意,您还可以使用对象定义样式属性,并使用camelCase编写属性。

鉴于您的图像可以通过yourdomain.com/images/Large/{...}.jpg访问。你应该做得很好

const path = (imageDescription[currentIndex]).imagePath;
const fullPath = `url(/images/Large/${path}.jpg)`;
return (
    <div style={{ backgroundImage: fullPath }} />
);

或者更快一点

const path = (imageDescription[currentIndex]).imagePath;
const backgroundImage = `url(/images/Large/${path}.jpg)`;
return (
    <div style={{ backgroundImage }} />
);

这是有效的,因为写一个对象作为qazxsw poi相当于写qazxsw poi

© www.soinside.com 2019 - 2024. All rights reserved.