[英]Combine multiple styled elements with styled-components
我知道我們可以使用樣式組件擴展或添加樣式到現有組件,例如react-router-dom
的Link
組件。 所述特征在此處指示。 但是,我的問題是,如何組合兩個或多個現有組件然后添加更多樣式?
就我而言,我有一個可重用的組件,用於span
、 p
和a
具有標准字體大小、字體粗細等的文本元素。同時,我想使用 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.