首页 > 解决方案 > `styled` 的包装函数

问题描述

目前我正在使用带有这样样式的组件的顺风。

const Container = styled.div.attrs({ 
    className: 'flex flex-col h-screen justify-center items-center' 
})`
    background-color: white;
`;

我想创建一个“包装器”函数,我可以这样调用

const Container = myStyled('div','flex flex-col h-screen justify-center items-center')`
    background-color: white;
`;

const Container2 = myStyled(Container,'text-6xl')`
    background-color: red;
`;

如何创建一个可以接受参数的标记模板文字字符串,然后将其传递给styled样式化组件?

标签: reactjstypescriptstyled-componentstemplate-literals

解决方案


样式化的组件可以被其他样式化的组件包裹,styled(otherStyledElement)如下所示:

import React from "react";
import styled from 'styled-components';

export default function App() {
  return (
    <Container>
      <h1>Hello CodeSandbox</h1>
      <Container2>
      <h2>Start editing to see some magic happen!</h2>
      </Container2>
    </Container>
  );
}

const Container = styled.div.attrs({ className: 'df'})`
  background: red;

`;

const Container2 = styled(Container).attrs({ className: 'df'})`
  background: blue;
`;

CodeSandbox 示例:https ://codesandbox.io/s/stack-63996579-styles-stacked-thwf3


推荐阅读