How to combine multiple inline style objects?

后端 未结 17 1569
难免孤独
难免孤独 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:56

    Object.assign() is an easy solution, but the (currently) top answer's usage of it — while just fine for making stateless components, will cause problems for the OP's desired objective of merging two state objects.

    With two arguments, Object.assign() will actually mutate the first object in-place, affecting future instantiations.

    Ex:

    Consider two possible style configs for a box:

    var styles =  {
      box: {backgroundColor: 'yellow', height: '100px', width: '200px'},
      boxA: {backgroundColor: 'blue'},
    };
    

    So we want all our boxes to have default 'box' styles, but want to overwrite some with a different color:

    // this will be yellow
    
    // this will be blue
    // this SHOULD be yellow, but it's blue.

    Once Object.assign() executes, the 'styles.box' object is changed for good.

    The solution is to pass an empty object to Object.assign(). In so doing, you're telling the method to produce a NEW object with the objects you pass it. Like so:

    // this will be yellow
    
    // this will be blue
    // a beautiful yellow

    This notion of objects mutating in-place is critical for React, and proper use of Object.assign() is really helpful for using libraries like Redux.

提交回复
热议问题