内联JSX中的动态CSS样式 [英] Inlining dynamic css style in JSX

查看:881
本文介绍了内联JSX中的动态CSS样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一百个图像,想要作为背景添加到页面中的100个 div 元素。

I have a hundred images which I want to add as a background to 100 div elements in my page.

我有一个共同点样式(样式),然后有可变部分,即图像。我使用 Object.assign 来创建 style1,style2,style3 等,它将静态元素与变量部分合并。

I have a common style (style), and then I have the variable part which is the image. I use Object.assign to create style1, style2, style3 etc, which merges the static with the variable part.

看起来像这样:

let style = {width:w, height:h, backgroundColor:'red', border :'5px solid red'}

let style1 = Object.assign(style, {backgroundImage:"url(" + img1 + ")"});
let style2 = Object.assign(style, {backgroundImage:"url(" + img2 + ")"});
....
let style100 = Object.assign(style, {backgroundImage:"url(" + img100 + ")"});


return (
  <div>
      <div style={style1}>1</div>
      <div style={style2}>2</div>
      <div style={style3}>3</div>

    ...

      <div style={style99}>99</div>
      <div style={style100}>100</div>
  </div>
);

这看起来很丑...

是否存在内联方式?像这样:

Is there an 'inline' way of doing this? Something like so :

<div style={Object.assign(style, {backgroundImage:"url(" + img1 + ")")}>1</div>
<div style={Object.assign(style, {backgroundImage:"url(" + img2 + ")")}>2</div>


推荐答案

您可以使用 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} />
        ))
    );
}

这篇关于内联JSX中的动态CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆