如何合并多个内联样式对象?

reactjs React.js

Pro小胖

2020-03-10

在React中,您可以清楚地创建一个对象并将其分配为内联样式。即。如以下所说的。

var divStyle = {
  color: 'white',
  backgroundImage: 'url(' + imgUrl + ')',
  WebkitTransition: 'all', // note the capital 'W' here
  msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};

var divStyle2 = {fontSize: '18px'};

React.render(<div style={divStyle}>Hello World!</div>, mountNode);

如何合并多个对象并将它们分配在一起?

第520篇《如何合并多个内联样式对象?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

10个回答
梅Sam路易 2020.03.10

内联样式的方式:

<View style={[styles.red, {fontSize: 25}]}>
  <Text>Hello World</Text>
</View>

<View style={[styles.red, styles.blue]}>
  <Text>Hello World</Text>
</View>

  <View style={{fontSize:10,marginTop:10}}>
  <Text>Hello World</Text>
</View>
神乐猿 2020.03.10

如果您想基于这样的条件添加样式,我已经为此建立了一个模块:

multipleStyles(styles.icon, { [styles.iconRed]: true })

https://www.npmjs.com/package/react-native-multiple-styles

神无Green前端 2020.03.10

为了扩展@PythonIsGreat所说的内容,我创建了一个全局函数来为我做这件事:

var css = function(){
    var args = $.merge([true, {}], Array.prototype.splice.call(arguments, 0));
    return $.extend.apply(null, args);
}

这将对象深深地扩展为新对象,并允许使用数量可变的对象作为参数。这使您可以执行以下操作:

return(
<div style={css(styles.base, styles.first, styles.second,...)} ></div>
);

var styles = {
  base:{
    //whatever
  },
  first:{
    //whatever
  },
  second:{
    //whatever
  }
}
Pro梅 2020.03.10

所以基本上我以错误的方式看待这个问题。从我的角度来看,这不是一个特定于React的问题,更多的是JavaScript问题,如何将两个JavaScript对象组合在一起(不破坏相似名称的属性)。

在这个StackOverflow答案中对此进行了解释。 如何动态合并两个JavaScript对象的属性?

在jQuery中,我可以使用extend方法。

小卤蛋Pro 2020.03.10

为了更进一步,您可以创建一个类名类似的帮助器函数:

const styleRules = (...rules) => {
  return rules.filter(Boolean).reduce((result, rule) => {
    return { ...result, ...rule };
  }, {});
};

然后在组件中有条件地使用它:

<div style={

  styleRules(
    divStyle,
    (window.innerWidth >= 768) && divStyleMd,
    (window.innerWidth < 768) && divStyleSm
  )

}>Hello World!</div>
ItachiHarry 2020.03.10

对于在React中寻找此解决方案的用户,如果您想在样式中使用传播运算符,则应使用:babel-plugin-transform-object-rest-spread。

通过npm模块安装它,并配置.babelrc如下:

{
  "presets": ["env", "react"],
  "plugins": ["transform-object-rest-spread"]
}

然后您可以使用...

const sizing = { width: 200, height: 200 }
 <div
   className="dragon-avatar-image-background"
   style={{ backgroundColor: blue, ...sizing }}
  />

更多信息:https : //babeljs.io/docs/en/babel-plugin-transform-object-rest-spread/

乐Eva 2020.03.10

您还可以将类与内联样式结合起来,如下所示:

<View style={[className, {paddingTop: 25}]}>
  <Text>Some Text</Text>
</View>
Tom小卤蛋 2020.03.10

您可以使用Object.assign()

在您的示例中,您将执行以下操作:

ReactDOM.render(
    <div style={Object.assign(divStyle, divStyle2)}>
        Hello World!
    </div>,
    mountNode
);

这将合并两种样式。如果有匹配的属性,则第二种样式将替换第一种样式。

正如Brandon所指出的,Object.assign({}, divStyle, divStyle2)如果要在divStyle未应用fontSize的情况下重用,则应使用

我喜欢用它来制作具有默认属性的组件。例如,这是一个带有默认值的无状态组件margin-right

const DivWithDefaults = ({ style, children, ...otherProps }) =>
    <div style={Object.assign({ marginRight: "1.5em" }, style)} {...otherProps}>
        {children}
    </div>;

因此,我们可以渲染如下内容:

<DivWithDefaults>
    Some text.
</DivWithDefaults>
<DivWithDefaults className="someClass" style={{ width: "50%" }}>
    Some more text.
</DivWithDefaults>
<DivWithDefaults id="someID" style={{ marginRight: "10px", height: "20px"}}>
    Even more text.
</DivWithDefaults>

这将给我们结果:

<div style="margin-right:1.5em;">Some text.</div>
<div style="margin-right:1.5em;width50%;" class="someClass">Some more text.</div>
<div style="margin-right:10px;height:20px;" id="someID">Even more text.</div>
西里宝儿 2020.03.10

您可以使用点差运算符:

 <button style={{...styles.panel.button,...styles.panel.backButton}}>Back</button
番长阳光 2020.03.10

如果您使用的是React Native,则可以使用数组符号:

<View style={[styles.base, styles.background]} />

查看有关此内容的详细博客文章

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android