如何从样式组件内部扩展(继承)全局CSS类

时间:2018-06-25 05:32:17

标签: css reactjs styled-components

是否可以将全局CSS类注入到styled-component中?

类似于在SASS中使用<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="600" height="250" style="border:1px solid #d3d3d3;"> </canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.save(); ctx.beginPath(); ctx.moveTo(20.5, 20.5); ctx.arcTo(20.5, 20.5, 100.5, 20.5, 0); ctx.arcTo(100.5, 20.5, 100.5, 70.5, 0); ctx.arcTo(100.5, 70.5, 20.5, 70.5, 0); ctx.arcTo(20.5, 70.5, 20.5, 20.5, 0); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(100.5, 20.5); ctx.arcTo(100.5, 20.5, 180.5, 20.5, 0); ctx.arcTo(180.5, 20.5, 180.5, 70.5, 0); ctx.arcTo(180.5, 70.5, 100.5, 70.5, 0); ctx.arcTo(100.5, 70.5, 100.5, 20.5, 0); ctx.closePath(); ctx.fill(); ctx.restore(); </script> </body> </html> &:extend在LESS中进行扩展。

此代码不适用于@extend样式:

globalCSS

globalClass确实会退出,甚至在内联使用时也会应用样式:

const extendedComponent = styled.div`
  &:extend(.globalClass) // I want this component to inherit all styles of .globalaCSS
  .otherStyles {
    ...
  }
`

1 个答案:

答案 0 :(得分:0)

您只需将“类名”添加到您的元素中, 但是如果您真的想继承或扩展。

以他们的示例作为参考:

const Button = styled.button`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

// We're extending Button with some extra styles
const TomatoButton = Button.extend`
  color: tomato;
  border-color: tomato;
`;

docs链接: https://www.styled-components.com/docs/basics#extending-styles