繁体   English   中英

如何避免使用样式化组件进行长时间的条件渲染?

[英]How to avoid long conditional rendering with styled components?

我正在使用许多不同的变量进行项目。 根据道具,它们将呈现某种颜色(例如)。 问题是,由于变量数量众多,我的代码最终会变得很长。 是否有清理此代码的解决方案?

这是一个例子:

变量:

const Variables = {
    Colors: {
        Primary50: "rgb(244, 246, 247)",
        Primary100: "rgb(209, 218, 225)",
        ...rest of colors
    },

    ...rest of variables
}

和样式化的组件:

const Component = styled.div<{ $color: number }>`
    background-color: ${({ $color }) =>
        $color === 50
            ? Variables.Colors.Primary50
            : $color === 100
            ? Variables.Colors.Primary100
            : ...rest};
`

我尝试了这样的事情,但它不起作用:

const Component = styled.div<{ $number: number }>`
    background-color: ${Variables.Colors.Primary[$number]};
`

感谢您的回答!

更好地为您的实例使用switch而不是三元运算符。 第二种方法Primary[$number]是错误的,它看起来像Variables.Colors.Primary.100您需要将Primary50完全括在方括号中。

const Variables = {
  Colors: {
    Primary50: 'rgb(244, 246, 247)',
    Primary100: 'rgb(209, 218, 225)',
  },
};

const Component = styled.div<{ $color: number }>`
  background-color: ${props => {
    switch (props.$color) {
      case 50:
        return Variables.Colors.Primary50;
      case 100:
        return Variables.Colors.Primary100;
      default:
        return 'white';
    }
  }};
`;

const Component2 = styled.div<{ $number: 50 | 100 }>`
  background-color: ${props => Variables.Colors[`Primary${props.$number}`]};
`;

function App() {
  return (
    <div className="App">
      <Component $color={100}>First example</Component>
      <Component2 $number={50}>Second example</Component2>
    </div>
  );
}

export default App;

编辑令人眼花缭乱的代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM