Styled-Components 与使用样式参数的功能组件

Styled-Components vs functional component using the style parameter

我只是问自己,除了节省一些 LOC 之外,在 React 中使用 styled-components 而不是自定义功能组件的原因是什么。示例代码:

const StyledButton = (props) => (
  <button
    style={{
      color: '#E8E8E8',
      padding: '8px 16px',
    }}
    {...props}
  />
);

const jsx = () => <div><StyledButton>Click Me!</StyledButton></div>;
const StyledButton = styled.button`
  color: '#E8E8E8';
  padding: '8px 16px';
`;

const jsx = () => <div><StyledButton>Click Me!</StyledButton></div>;

亲切的问候, 托马斯

借助样式组件,您可以充分利用 css 的全部功能,这意味着您可以:

  • 覆盖子标签的 css 和 类
  • 使用伪类如:visited:first
  • 使用hover和其他ui状态
  • 轻松使用css变量

只是举几个例子,但显然 css 默认情况下可以做的任何其他事情都需要 ui 额外 javascript 来处理普通样式。

您还可以阅读有关 motivation behind styled-components here 的更多信息。