css - 根据其 Prop 有条件地在组件上应用实用程序类的最佳方法

标签 css reactjs vue.js refactoring vue-component

我正在使用 Vue.js(尽管我的问题对任何框架都有效),您可以在其中传递一个简单的对象和 truthy键作为类应用。 例如。 <div :class="{ 'class1': prop1, 'class2', prop2 }">Hello</div> .如果prop1是真的,class1适用。如果两个 Prop 都为真,则 class1class2申请。

此外,我正在使用 Atomic/Utiliy 类。因此,其中没有具有多个属性的类,而是 color:red我用 C(red) , 对于 background-color:blue我用 Bgc(blue)等等……

以此为基础,我有一个具有以下 Prop 的按钮组件:

  1. 主题 - 具有主要值(value)、次要值(value)。
  2. 反转 - 真/假
  3. 禁用 - 真/值

为那么多相互关联的 Prop 创建一个类对象变得有点困惑:

{
'Bdc(color1) Bdc(color2):h Bdc(color3):a': this.theme === 'primary' && !this.linkOnly,
'Bdc(color4) Bdc(color5):h Bdc(color5):a': this.theme === 'positive' && !this.linkOnly,
'Bdc(color1) Bdc(color2):h Bdc(color4):a': this.theme === 'negative' && !this.linkOnly,
'Bdc(color3) Bdc(color3):h Bdc(color3):a': (this.theme === 'default' && !this.linkOnly) ||
(!this.theme && !this.linkOnly),

'C(color1) C(color2):h C(color3):a':
    this.theme === 'primary' && (this.linkOnly || this.inverted),
'C(color3) C(color4):h C(color5):a':
    this.theme === 'positive' && (this.linkOnly || this.inverted),
'C(color2) C(color3):h C(color4):a':
    this.theme === 'negative' && (this.linkOnly || this.inverted),
'C(color5) C(color6):h C(color7):a':
    (this.theme === 'default' && (this.linkOnly || this.inverted)) ||
    (!this.theme && (this.linkOnly || this.inverted)),
'C(color1)': !(this.linkOnly || this.inverted)

如您所见,那里的条件很难阅读。并且添加一些新的 prop 会使正确实现变得更加困难。

还有一件更重要的事情:我正在使用的原子 CSS 库要求最终类出现在代码中,因为它解析并将它们放入 CSS 中。所以'Bgc(' + someVariable + ')'不会工作,因为它不是我们想要的 final类。

我正在寻求有关如何重构这些条件以使样式易于使用原子/实用程序类进行管理的帮助。

最佳答案

您可以将所有逻辑移动到 computed属性:

function getBtnClass () {
  let classes = []
  if (this.theme === 'primary') classes.push('Bdc(color1)', 'Bdc(color2):h')
  ...
  return classes.join(' ')
}

并将其传递给模板:<div class='getBtnClass'>...</div>

关于css - 根据其 Prop 有条件地在组件上应用实用程序类的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52040101/

相关文章:

html - 根据图像宽度调整文本

html - 绝对定位元素导致元素在IE中内联显示

javascript - 多个元素的条件渲染

ReactJs 覆盖 Font Awesome 图标

vue.js - 使用 v-model 在 Vue-Electron App 启动时初始化 vuex 存储数据

javascript - 如何使用 Nightwatch.js 滚动到页面底部

html - 保持行中的列宽设置为 "display: table"

更改后CSS不刷新

javascript - 在 react 中将函数作为 Prop 传递,无法读取未定义的属性 '_handleEvent'

javascript - Vuejs 布局和页面组件