基于道具的3种风格类型的最佳方法是什么?
与Bootstrap一样,旨在拥有默认,小型和中型。
这里我有默认值和小号,但我如何考虑大号呢?
const Button = styled.button`
background: teal;
border-radius: 8px;
color: white;
height: ${props => props.small ? 40 : 60}px;
width: ${props => props.small ? 60 : 120}px;
`;
class Application extends React.Component {
render() {
return (
<div>
<Button small>Click Me</Button>
<Button>Click Me</Button>
<Button large>Click Me</Button>
</div>
)
}
}
答案 0 :(得分:1)
这是我使用的选项的缩写示例。
/* import separate css file from styles.js */
import * as Styles from './styles';
/* concat styles based on props */
const ButtonBase = styled.button`
${Styles.buttonbase};
${props => Styles[props.size]};
${props => Styles[props.variant]};
`;
const Button = ({ size, variant, ...rest }) => (
<ButtonBase
size={size}
variant={variant}
{...rest}
...
在样式文件中(为简洁起见,删除了css)
import { css } from 'styled-components';
/* styles common to all buttons */
export const buttonbase = css`...`;
/* theme variants */
export const primary = css`...`;
export const secondary = css`...`;
export const tertiary = css`...`;
/* size variants */
export const small = css`...`;
export const medium = css`...`;
export const large = css`...`;
答案 1 :(得分:1)
我也认为这是一个解决方案:
const ButtonBase = styled.button`
padding: ${props => {
if (props.xl) return props.theme.buttonSize.xl;
if (props.lg) return props.theme.buttonSize.lg;
if (props.md) return props.theme.buttonSize.md;
if (props.sm) return props.theme.buttonSize.sm;
return props.theme.buttonSize.nm;
}};
`