San*_*tas 8 javascript reactjs styled-components
我知道,我们可以扩展或添加样式到现有的组件与类似风格的组件Link的组件react-router-dom。所述特征在此处指示。但是,我的问题是,如何组合两个或多个现有组件然后添加更多样式?
就我而言,我有一个可重用的组件用于文本元素,例如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" />
</>
);
Run Code Online (Sandbox Code Playgroud)
任何建议将不胜感激。
我的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} />);
Run Code Online (Sandbox Code Playgroud)
您可以使用 css helper 为此使用 mixin。假设您将 for 的代码TextElement放在一个spacedmixin 中,例如:
import { css } from 'styled-components';
const spaced = css`
margin: 10px 0;
`;
Run Code Online (Sandbox Code Playgroud)
另一个混入 Link
const styledLink = css`
color: blue;
`;
Run Code Online (Sandbox Code Playgroud)
然后你可以定义你MyLink的:
import styled from 'styled-components'
const MyLink = styled(Link)`
${spaced}
${styledLink}
`;
Run Code Online (Sandbox Code Playgroud)
Nic*_*Diz -1
样式组件可以是自定义组件的包装器。例如:
Your style component:
export const CustomSpanWrapper = styled.div`
span {
...your-styles
}
`;
Your other component:
<CustomSpanWrapper>
<CustomSpan>
</CustomSpanWrapper>
Run Code Online (Sandbox Code Playgroud)