簡體   English   中英

將多個樣式元素與樣式組件組合在一起

[英]Combine multiple styled elements with styled-components

我知道我們可以使用樣式組件擴展或添加樣式到現有組件,例如react-router-domLink組件。 所述特征在此處指示。 但是,我的問題是,如何組合兩個或多個現有組件然后添加更多樣式?

就我而言,我有一個可重用的組件,用於spanpa具有標准字體大小、字體粗細等的文本元素。同時,我想使用 react-router-dom 的 Link 組件。 目前,我有這樣的事情:

import styled from 'styled-components';
import { Link } from 'react-router-dom';
import { TextElement } from '../common';

/*
Can I do something like this?
const MyLink = styled(Link, TextElement)`
    margin: 10px 0;
`;

or this?
const MyLink = styled([Link, TextElement])`
    margin: 10px 0;
`;
*/

const MyPage = props => (
   <>
       <MyLink to="/next-page" />
   </>
);

任何建議將不勝感激。

編輯

我的TextElement組件就像這樣:

const Element = styled.span`
   font-size: 13px;
   font-weight: 500;
`;

// These styles are sample only. Actual styles depend on a "variant" prop.
// I did not show it here since it doesn't have to do with the question I'm asking.

export default ({ tag }) => (<Element as={tag} />);

您可以使用 css helper 為此使用 mixin。 假設您將TextElement的代碼放在一個spaced mixin 中,例如:

import { css } from 'styled-components';

const spaced = css`
  margin: 10px 0;
`;

還有另一個用於Link mixin

const styledLink = css`
  color: blue;
`;

然后您可以將您的MyLink定義為:

import styled from 'styled-components'

const MyLink = styled(Link)`
  ${spaced}
  ${styledLink}
`;

樣式組件可以是自定義組件的包裝器。 例如:

Your style component:

export const CustomSpanWrapper = styled.div`
    span {
        ...your-styles
    }
`;

Your other component:

<CustomSpanWrapper>
    <CustomSpan>
</CustomSpanWrapper>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM