【问题标题】:How to extend and override a style object reactjs如何扩展和覆盖样式对象reactjs
【发布时间】:2025-12-11 02:20:13
【问题描述】:

我有一个类似于下面的基本样式对象:

const baseGridStyle = {
  gridStyle: {
    '& .ag-header-row, .ag-filter-input:input': {
      fontSize: '14px',
      backgroundColor: COLORS.dark_blue,
      minWidth: '100%',
    }
  }
}

现在,我正在尝试扩展和覆盖上述样式对象,如下所示:

  const extendedGridStyle = (theme) => ({
  gridStyle: {
    '& .ag-header-row': {
      fontSize: '16px'
    }
  }
})

我尝试使用如下扩展语法扩展基本样式,但它用扩展的GridStyle 覆盖了baseGridStyle 对象的gridStyle 属性

const extendedGridStyle = (theme) => ({
  ...baseGridStyle,
  gridStyle: {
    '& .ag-header-row': {
      fontSize: '16px'
    }
  }
})

我尝试使用 lodash 的合并功能来合并两个对象。由于 extendedGridStyle 是一个函数,merge 函数不会合并样式。有没有办法做到这一点(可能是类似 jss 的方式)?

由于此问题,我无法继续进行。对此的任何帮助将不胜感激。提前致谢。干杯!

更新 1: 我尝试了 Stuart 下面建议的答案。会发生什么,如果我有一个

'& .ag-header-row' //class A
{
 fontSize: '14px,
 border-width: '1px'
}

baseGridStyle 中,我有一个

'& .ag-header-row' //class A
{
fontSize: '16px
}

在extendedGridStyle 中,基础网格中的A 类被extendedGridStyle 的A 类覆盖。有没有办法在只覆盖 fontSize 的同时保留边框宽度。

【问题讨论】:

    标签: reactjs material-ui jss


    【解决方案1】:

    因此,如果您打算在不丢失原始密钥的情况下将它们合并在一起,那么您正在寻找的是:

    const extendedGridStyle = (theme) => ({
      gridStyle: {
         ...baseGridStyle.gridStyle,
        '& .ag-header-row': {
          fontSize: '16px'
        }
      }
    })
    

    最终会变成这样:

    const extendedGridStyle = (theme) => ({
    
      gridStyle: {
         '& .ag-header-row, .ag-filter-input:input': {
          fontSize: '14px',
          backgroundColor: COLORS.dark_blue,
          minWidth: '100%',
        },
        '& .ag-header-row': {
          fontSize: '16px'
        }
      }
    })
    

    我认为这就是你要找的。​​p>

    编辑: 所以我的理解是 A 和 B 的类是相同的,你想将它们合并在一起。不丢失 cssProps。如果是这样,那么您可以使用类似的功能将它们深度合并

    const merge = (target, source) => {
      // Iterate through `source` properties and if an `Object` set property to merge of `target` and `source` properties
      for (const key of Object.keys(source)) {
        if (source[key] instanceof Object) Object.assign(source[key], merge(target[key], source[key]))
      }
    
      // Join `target` and modified `source`
      Object.assign(target || {}, source)
      return target
    }
    

    你会做以下事情:

    const extendedGridStyle = (theme) => (merge(baseGridStyle,{
    
      gridStyle: {
        '& .ag-header-row': {
          fontSize: '16px'
        }
      })
    })
    

    希望对你有帮助

    【讨论】:

    • 感谢您的及时回复。我尝试了上述解决方案。发生的情况是,如果我在 baseGridStyle 中有一个类 A {prop1: value1, prop2: value2} 并且我在 extendedGridStyle 中有一个类 A {prop1: value3},则基本网格中的类 A 将被扩展网格样式的类 A 覆盖.有没有办法保留 prop2 而只覆盖 prop1
    • 当您说 A 类时,您的意思是 css 类中的类还是 js 对象?
    • 对造成的混乱感到抱歉。我的意思是css类。考虑 '& .ag-header-row' 而不是 A 类