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

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


当前回答

你可以用Object.assign()来实现。

在你的例子中,你会这样做:

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

这样两种风格就合并了。如果有匹配的属性,则第二个样式将取代第一个样式。

正如Brandon所指出的,您应该使用Object。分配({},divStyle, divStyle2)如果你想重用divStyle没有fontSize应用到它。

我喜欢使用它来创建具有默认属性的组件。例如,这里有一个默认右边距的无状态组件:

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>

其他回答

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

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

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

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

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




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

为了更进一步,你可以创建一个类名类的helper函数:

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>

与React Native不同,我们不能在React中传递样式数组,比如

<View style={[style1, style2]} />

在React中,我们需要在将其传递给style属性之前创建单个样式对象。如:

const Header = (props) => {
  let baseStyle = {
    color: 'red',
  }

  let enhancedStyle = {
    fontSize: '38px'
  }

  return(
    <h1 style={{...baseStyle, ...enhancedStyle}}>{props.title}</h1>
  );
}

我们使用ES6 Spread运算符来组合两种风格。你也可以使用Object.assign()来达到同样的目的。

如果你不需要将你的样式存储在一个变量中,这也可以工作

<Segment style={{...segmentStyle, ...{height:'100%'}}}>
    Your content
</Segment>

你可以使用展开运算符:

 <button style={{...styles.panel.button,...styles.panel.backButton}}>Back</button