【问题标题】:How to execute and merge multiple functions result by using Lodash如何使用 Lodash 执行和合并多个函数结果
【发布时间】:2018-11-03 10:50:59
【问题描述】:

假设我们有 2 个不同的函数(或更多),它们接受来自某个执行器的一个参数并返回结果对象。让我举个例子:

const style_1 = theme => ({
  header : {
      color : theme.primary
    }
})

const style_2 = theme => ({
  header : {
      backgroundColor : theme.secondary,
      color : "red"
    }
})

我想执行它们并将结果对象合并为一个!如果是对象,这是一项微不足道的任务,例如。

const style_1 = {
  header : {
      color : theme.primary
    }
}

const style_2 = {
  header : {
      backgroundColor : theme.secondary,
      color : "red"
    }
}

 const res = {...style_1, ...style_2}

预期结果是

 { 
   header :
     { 
       backgroundColor : "black",
       color : "red"
      }
}

但在函数的情况下,它变得有点烦人。

所以问题是。是否有可能实现我想要的? (通过 Lodash 或使用其他方式)

我决定我可能会创建类似的东西

const style_1 = theme => ({
    header : {
        color : theme.secondary
        backgroundColor : "black"
    },
    footer : {
        color : "purple"
    }
})

const style_2 = (theme, extendStyles) => {
    const extendStyles = extendStyles(theme);

    return {
        header : {
            color : theme.primary,
            ...extendsStyles.header
        },
        ...extendStyles
    }
}

但是这个解决方案有点难看,因为我应该以可能被覆盖的每一种风格来照顾这个东西。也许存在一些实用程序/帮助程序可以帮助以更好的方式处理它?

附:不要问我这个有趣的要求,它只是 MaterilUI 的 withStyle 功能,我想知道如何正确处理它。

感谢您的帮助。

【问题讨论】:

    标签: javascript lodash material-ui jss


    【解决方案1】:

    您可以使用_.invokeMap()_.merge() 从一组样式函数和一个主题中生成一个组合样式对象:

    const applyTheme = (styles, theme) =>
      _.merge(..._.invokeMap(styles, _.call, null, theme));
    
    const style_1 = theme => ({
      header : {
          color : theme.primary,
          border: `1px solid ${theme.primary}`
        }
    })
    
    const style_2 = theme => ({
      header : {
          backgroundColor : theme.secondary,
          color : "red"
        }
    })
    
    const theme = { primary: 'red', secondary: 'blue' }
    
    const result = applyTheme([style_1, style_2], theme)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      相关资源
      最近更新 更多