为导入的样式化组件设置样式

Style an imported styled-component

我有以下组件:

const StyledH3 = styled.h3`
  direction: ${(props) => (props.isRTL ? 'rtl' : 'ltr')};
`;

const H3 = ({ children }) => (
  <StyledH3 isRTL={isChildrenRTL(children)}>
    {children}
  </StyledH3>
);

export default H3;

我想扩展它的样式,例如在不同的文件中:

import { H3 } from 'components';

const Title = styled(H3)`
  background-color: red;
`;

我怎样才能做到这一点?

根据 styled-component 文档,您应该这样做。

export const StyledH3 = styled.h3`
 direction: ${(props) => (props.isRTL ? 'rtl' : 'ltr')};
`;
const H3 = ({ children }) => (
  <StyledH3 isRTL={isChildrenRTL(children)}>
    {children}
  </StyledH3>
);
export default H3;

然后在您需要的其他文件中,执行类似的操作。

import H3, { StyledH3  } from 'components';

const Title = StyledH3 .extend`
  background-color: red;
`;

参考 Extending styles in styled-components

请注意,您只能扩展 styled-component 的样式,而不能扩展 styled-component 的 React 哑组件 class。

我设法通过使用 extendwithComponent 方法解决了这个问题。因此,我没有导出组件,而是导出了带有所有逻辑的样式化组件:

const TwoWayP = styled.p`
  direction: ${props => isChildrenRTL(props.children) ? 'rtl' : 'ltr' };
`;

然后扩展样式组件,如果需要(我也需要)更改它的标签:

const TwoWayH3 = TwoWayP.withComponent('h3');

const Title = TwoWayH3.extend`
  background-color: red;
`;

所以我的解决方案的主要部分是在没有 React 组件的情况下将逻辑移动到样式化组件中

您需要在导出的组件上公开 className 属性,以便它可以接收新的 className:

const StyledH3 = styled.h3`
    direction: ${(props) => (props.isRTL ? 'rtl' : 'ltr')};
`;

const H3 = ({ children, className }) => ( // Note - className prop.
    <StyledH3 
        className={className} // Need to add this here 
        isRTL={isChildrenRTL(children)}
    >
        {children}
    </StyledH3>
);
export default H3;

然后您可以按照您的建议在不同的文件中扩展您的组件样式:

import H3 from 'components';

const Title = styled(H3)`
    background-color: red;
`;

参考linkhttps://www.styled-components.com/docs/basics#styling-any-components

使用 styled-components v4 "as" :

h3.js

const StyledH3 = styled.h3`
  color:red;
`;

export const H3 = ({ children }) => (
  <StyledH3>{children}</StyledH3>
);

card.js

import { H3 } from 'components';

const Title = styled.div`
   border-bottom: 1px solid red;
`;

export const Card = (props) => (
  <div>
     <Title as={H3} />   <----- using "as" --------
     <p>...</p>
  </div>
);