在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);

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


当前回答

    const style1 = {
        backgroundColor: "#2196F3", 
    }
    
    const style2 = {
        color: "white", 
    }

    const someComponent = () => {
        return <div style={{ ...style1, ...style2 }}>This has 2 separate styles</div> 
    }
    

注意双花括号。播音接线员是你的朋友。

其他回答

为了扩展@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
  }
}

所以基本上我看问题的方式是错误的。从我所看到的,这不是一个React特定的问题,更多的是一个JavaScript问题,在我如何结合两个JavaScript对象在一起(没有打击类似命名的属性)。

在这个StackOverflow的答案中,它解释了这一点。如何动态合并两个JavaScript对象的属性?

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

要在react js中添加多个内联样式,你可以这样做

<div style={{...styles.cardBody,...{flex:2}}}>

在React中有多个内联样式。

<div onClick={eleTemplate} style={{'width': '50%', textAlign: 'center'}}/>

需要合并对象中的属性。 例如,

const boxStyle = {
  width : "50px",
  height : "50px"
};
const redBackground = {
  ...boxStyle,
  background: "red",
};
const blueBackground = {
  ...boxStyle,
  background: "blue",
}




 <div style={redBackground}></div>
 <div style={blueBackground}></div>