避免在样式组件中重复代码

Avoid repeating code in styled-components

我在 ReactJS 的两个不同组件上使用了以下相同样式的组件。我想知道是否可以使用一种混合存储在另一个文件中并导出它们,然后在每个 ReactJS 组件上调用它们?这样可以避免重复代码。

// Repeated styles

const TitleInflow = styled.h1`
  text-align: center;
  margin-top: 70px;
  padding-bottom: 50px;
`;

const Table = styled.table`
  margin: 0 auto;
  margin-top: 100px;
`;

const ThTable = styled.th`
  padding-right: 20px;
  padding-left: 20px;
  padding-bottom: 10px;
`;

解决方案 1:您可以创建一个通用文件,例如:

Common.js

const Common = `
 // style you want.
 padding: 5px; 
 color: red;
`
export default Common

并将其添加到您的样式组件中,例如

Components.js

import Common from './common'

const TitleInflow = styled.h1`
  ${Common};
  text-align: center;
  margin-top: 70px;
  padding-bottom: 50px;
`;

解决方案 2:您可以创建一个组件并扩展它:

这里有一个要扩展的组件:

const Component = styled.p`
   color: red; 
   fontSize: 12px;
`

像这样扩展样式:

const NewComponent = styled(Component)`
    // new style you want.
    display: flex;
`

如果你想用另一个 html 标签扩展样式,你可以在使用它时喜欢它:

 <NewComponent as="h1"/>