且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

内联JSX中的动态CSS样式

更新时间:2023-01-27 11:43:22

您可以使用 proposal-object-rest-spread (您需要babel的对象剩余分布转换),以将背景图像与样式对象合并。此外,您可以使用模板文字来注入img动态部分转换为静态部分:

You can use proposal-object-rest-spread (you'll need babel's Object rest spread transform) to merge the background image with the style object. In addition you can use a template literal to inject the img dynamic part into the static part:

<div style={{ ...style, backgroundImage: `url(${img1})` }}>1</div>

btw-所有这些都应该循环执行,可能使用 Array#map ,您可能想为每个组件创建一个组件图像。

btw - all of this should be done in a loop, probably using Array#map, and you might want to create a component for each image.

您将拥有一系列图像['img1','img2','img3'等...]。

You'll have an array of images ['img1', 'img2', 'img3', etc...].

图像组件应该是这样的:

An image component would be something like this:

const Image = ({ style, img, text }) => (
    <div style={{ ...style, backgroundImage: `url(${img}.png)` }}>{text}</div>
);

外部组件的渲染可能看起来像这样:

And the outer component's render would probably look like this:

render() {
    const {images} = this.props;

    return (
        images.map((img, index) => (
            <Image style={style} img={img} text={index} key={img} />
        ))
    );
}