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

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


当前回答

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

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

其他回答

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

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

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

数组表示法是react native中组合样式的最佳方式。

这展示了如何组合2个Style对象,

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

这展示了如何组合样式对象和属性,

<Text style={[styles.base, {color: 'red'}]} >Test </Text>

这将适用于任何react本机应用程序。

我已经为此构建了一个模块,如果你想根据条件添加样式 是这样的:

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

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

你可以使用作曲

 const styles = StyleSheet.create({
        divStyle :{
          color: 'white',
          backgroundImage: 'url(' + imgUrl + ')',
          WebkitTransition: 'all', // note the capital 'W' here
          msTransition: 'all' // 'ms' is the only lowercase vendor prefix
        },
        divStyle2 :{fontSize: '18px'}
    })
        
        React.render(<div style={StyleSheet.compose(styles.divStyle, styles.divStyle2)}>Hello World!</div>, mountNode);

OR

 React.render(<div style={[styles.divStyle, styles.divStyle2]}>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>