编写具有样式组件的react组件,哪一个更好



给定要在网站上共享的一些按钮,以下两种方法中哪一种最好使用:

const ButtonA = styled.button`
color: 'red'
`
const ButtonB = styled.button`
color: 'blue'
`

像这个一样使用

const Home = () => {
return <ButtonA>Button A</ButtonA><ButtonB>Button B</ButtonB>;
}

const Button = styled.button`

${({variant }) => variant === 'A' && `
color: red;
`
${({variant }) => variant === 'B' && `
color: blue;
`
`

像这样使用:

const Home = () => {
return <Button variant="A">Button A</Button><Button variant="B">Button B</Button>;
}

请说明使用一种方法的原因、优点和缺点。

始终取决于具体情况。通常最好像第二个例子那样传递变体道具。第一种解决方案的问题是必须重复相同的代码。最好这样做:

const Button = styled.button`
// basic styles here
`
const ButtonWithDifferentStyles = styled(Button)`
// additional styles here
`

最新更新