减少样式组件中的重复代码
我在一个 React 项目中使用样式组件,想知道是否有一种方法可以减少这 3 个重复的块,唯一的区别是边框的颜色。
最初,我正在考虑创建一个对象来映射可能的警报值(成功、警告、危险),并添加适当的颜色作为它们的键,但是我不确定将该对象放在哪里。
const customStyles = {
${({ alert }) =>
alert === "success" &&
css`
border: 1px solid green;
`}
${({ alert }) =>
alert === "warning" &&
css`
border: 1px solid orange;
`}
${({ alert }) =>
alert === "danger" &&
css`
border: 1px solid red;
`}
}
const Input = styled.input`
${customStyles}
`;
I'm using styled-components in a react project, and wondering if there's a way to reduce these 3 blocks that are repeating, with the only difference being the color of the border.
Initially, I'm thinking of creating an object that maps out the possible alert values (success, warning, danger), and add appropriate color as their keys, however I'm not sure where it to put that object.
const customStyles = {
${({ alert }) =>
alert === "success" &&
css`
border: 1px solid green;
`}
${({ alert }) =>
alert === "warning" &&
css`
border: 1px solid orange;
`}
${({ alert }) =>
alert === "danger" &&
css`
border: 1px solid red;
`}
}
const Input = styled.input`
${customStyles}
`;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以重用一个根据值返回正确颜色的函数怎么样?
像这样的事情:
How about a function you can reuse that returns the right color based on the value?
Something like this: