1

我已经开始styled-components在我的一个项目中使用。我想知道在使用它的容器中覆盖/扩展它们的推荐方法。

例如:

一个可重用的Button组件:

const Button = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid red;
  color: red;
`;

现在假设我在一个部分中使用它,但需要应用左边距。我可以通过以下几种方式做到这一点:

延长:

const NewButton = styled(Button)`
  margin-left: 10px;
`;

内联样式:

<Button style={{marginLeft: '10px'}}>Normal Button</Button>

如果要覆盖的规则超过 3,4 条,则扩展似乎是最好的方法。

margin但是对于像,这样的单个规则paddingdisplay: none它可能会非常频繁地出现,每次创建一个新的包装器都会增加很多样板文件。内联样式在这方面效果很好,但它们也有自己的缺陷

可以在大型应用程序中很好地扩展的最佳方法是什么?

4

1 回答 1

0

对于在用法之间可能略有不同的样式,我建议props在定义属性之前使用样式中的对象来计算属性。

有了这个,你的按钮可能看起来像这样:

// style that will always apply margin-left even if it doesn't exist
const Button = styled.button`
  margin-left: ${props => props.marginLeft}
`
// style that won't apply margin-left if it doesn't exist
const Button = styled.button`
  ${props => props.marginLeft && `
    margin-left: ${props.marginLeft};
  `}
`

// button with margin-left: 10px
<Button marginLeft="10px" />

// button without margin-left
<Button />

实现这一点需要做更多的工作,但是当样式可以在相似元素之间更改时,这是非常值得的。

于 2019-03-10T20:13:33.280 回答