How to combine multiple inline style objects?

后端 未结 17 1500
难免孤独
难免孤独 2020-11-28 18:54

In React you can clearly create an object and assign it as an inline style. i.e.. mentioned below.

var divStyle = {
          


        
17条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 19:51

    You can do this with Object.assign().

    In your example, you would do:

    ReactDOM.render(
        
    Hello World!
    , mountNode );

    That will merge the two styles. The second style will replace the first if there are matching properties.

    As Brandon noted, you should use Object.assign({}, divStyle, divStyle2) if you want to reuse divStyle without the fontSize applied to it.

    I like to use this to make components with default properties. For example, here's a little stateless component with a default margin-right:

    const DivWithDefaults = ({ style, children, ...otherProps }) =>
        
    {children}
    ;

    So we can render something like this:

    
        Some text.
    
    
        Some more text.
    
    
        Even more text.
    
    

    Which will give us the result:

    Some text.
    Some more text.
    Even more text.

提交回复
热议问题