我想将许多预先存在的按钮 CSS 定义压缩到一个样式组件中。通过使用条件扩展我的定义,我找到了积极的结果,但是我已经到了定义变得相当大的地步,我想知道是否有一种方法可以用某种 switch
来压缩我的定义。将 CSS 抽象为返回的内容的语句?
用例:
我有一个自定义 <Button>
需要几个 Prop 的组件 theme
和 type
,所以我的按钮的一个例子是:
<Button theme="primary" category="my-cat">Click me</Button>
theme
和 category
每个将采用 2 个不同的变量,所以到目前为止没有什么疯狂的想法......
到目前为止,我的定义已经变得臃肿了:
export const Button = styled.a`
background: lightgrey;
// ... More standard stuff
${props => (props.theme === 'one' || props.theme === 'two') && `
// ... more CSS
`}
${props => (props.theme === 'one' && props.category === 'cat1') && `
// ... more CSS
`}
${props => (props.theme === 'one' && props.category === 'cat2') && `
// ... more CSS
`}
`;
是否可以做一些事情,以便我可以将我的 props 传递给一个函数,并根据这些 props 和条件操作返回附加的 CSS?像这样的东西:
function styleMyEl(props) {
switch(props) {
case (props.theme === 'one' || props.theme === 'two'):
// return my additional css
case ...
default:
return;
}
}
export const Button = styled.a`
background: lightgrey;
// ... More standard stuff
${props => styleMyEl(props)}
最佳答案
您可以尝试返回 css
block :
import React from 'react';
import ReactDOM from 'react-dom';
import styled, { css } from 'styled-components';
function styleMyEl(theme) {
switch (theme) {
case 'one':
return css`
background: black;
color: pink;
`;
default:
return css`
background: pink;
color: black;
`;
}
}
export const Button = styled.a`
${props => styleMyEl(props.theme)}
`;
const App = () => {
return (
<>
<div>
<Button theme="one">Button</Button>
</div>
<div>
<Button>Button</Button>
</div>
</>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
这是一个普遍的问题,你可以查看styled-map
试图解决这个问题的库:
With Styled Components alone, you'll often do something like this:
const Button = styled.button`
color: ${props =>
props.primary && '#0c0' ||
props.warning && '#c00' ||
props.info && '#0cc' ||
'#ccc'
};
border: 2px solid ${props =>
props.primary && '#0c0' ||
props.warning && '#c00' ||
props.info && '#0cc' ||
'#ccc'
};
font-size: ${props =>
props.small && '8px' ||
props.medium && '18px' ||
props.large && '32px' ||
'16px'
};
`;
<Button primary large>Submit</Button>
Here's the same component using
styled-map
:
import styledMap from 'styled-map';
const buttonColor = styledMap`
primary: #0c0;
warning: #c00;
info: #0cc;
default: #ccc;
`;
const Button = styled.button`
color: ${buttonColor};
border: 2px solid ${buttonColor};
font-size: ${styledMap`
large: 32px;
small: 8px;
medium: 18px;
default: 16px;
`};
`;
<Button primary large>Submit</Button>
你应该寻找相关的styled-components
utilities或者自己实现一个,更多例子是styled-is
, styled-by
关于javascript - 将多个条件语句压缩到样式组件中的一个开关中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59376399/