【问题标题】:Setting background image within React component在 React 组件中设置背景图像
【发布时间】:2020-09-16 10:01:12
【问题描述】:

我目前正在摆弄这个transformationsn-p,我想将框的背景更改为图像,而不是渐变。但是,它似乎不起作用。


 <div
          className="element"
                style={{
                width: element.width,
                height: element.height,
                backgroundImage: this.state.backgroundImage,
                ...styles,
                }}
                                        
 >
import BackgroundImage from './door1.png';
...
...
constructor(props) {
        super(props);
        this.state = {
            elements: [
                {
                    id: "el-3",
                    x: 100,
                    y: 225,
                    scaleX: 1,
                    scaleY: 1,
                    width: 100,
                    height: 100,
                    angle: 0,
                    backgroundImage: {BackgroundImage},
                    classPrefix: "tr2",
                    text: "Scale Disabled",
                    styles: {
                        padding: 5,
                    },
                    disableScale: false,
                },
            ],
            offsetX: 40,
            offsetY: 20,
            zoom: 1,
        };

        this.workspaceRef = React.createRef();
    }

有什么想法吗? 我也尝试做这样的事情: Setting Background-Image in React , Syled Components Background Image React , Setting background image as prop in react

但它似乎不起作用

我也试过把它放在div里面,像这样:

<div
    className="element"
    style={{
        width: element.width,
        height: element.height,
        backgroundImage: this.state.backgroundImage,
        ...styles,
    }}
    
>
    <img src={element.backgroundImage.BackgroundImage} />
    {element.text}
</div>

但它最终看起来像这样: Door

【问题讨论】:

    标签: css reactjs


    【解决方案1】:

    稍微修改一下

    更改您的 json 对象,例如

    ...
        backgroundImage: BackgroundImage, //without curly braces
    ....
    

    在 div 中

        style={{
           ....
           backgroundImage: `url("${element.backgroundImage}")`,
           ...styles
        }}
    

    查看here

    【讨论】:

    • 非常感谢@kalhan.toress,您知道如何自动将图像放入边框内吗?
    • 我试图显示的图像看起来像这样:imgur.com/3caKG1u 当它应该看起来像这样:imgur.com/YDJCbc4
    • @ojbl 尝试添加background-size: 100% 100%; 样式
    猜你喜欢
    • 2019-08-11
    • 2018-01-23
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 2012-08-04
    相关资源
    最近更新 更多