有没有办法声明具有不同主要元素的样式组件?
Is there a way to declare styled component with different main elements?
我需要创建 2 个相似样式的组件,它们将共享它们的样式但使用不同的 HTML 元素。
有一种方法可以在运行时使用 "as" 属性 (),但我有一个特定的导出,我需要使用默认值,但我需要它以某种方式不使用它所以 Link 样式组件是 "styled.a" 和样式 Link 组件是 "styled.span",我试着做这样的事情:
export const StyledLink = styled.span(`
color: ${props => props.theme.colors.mainLinkColor};;
text-decoration: underline;
&:hover {
color: ${props => props.theme.colors.textAccent};
text-decoration: underline;
}
`);
export const Link = <StyledLink as={RRLink} />;
这显然是行不通的...所以有没有办法让 Link 模仿 StyledLink 样式,但使用 "a" 标签而不是 "span" ?
只需从 styled-components
导入并使用 css
,如下所示:
import React from "react";
import ReactDOM from "react-dom";
import styled, { css } from 'styled-components';
const sharedStyles = css`
background-color: gold;
`;
const Div = styled.div`
${sharedStyles}
`;
const Button = styled.button`
${sharedStyles}
`;
const App = () => (
<>
<Div>Hello Div</Div>
<Button>Hello Button</Button>
</>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
我需要创建 2 个相似样式的组件,它们将共享它们的样式但使用不同的 HTML 元素。
有一种方法可以在运行时使用 "as" 属性 (),但我有一个特定的导出,我需要使用默认值,但我需要它以某种方式不使用它所以 Link 样式组件是 "styled.a" 和样式 Link 组件是 "styled.span",我试着做这样的事情:
export const StyledLink = styled.span(`
color: ${props => props.theme.colors.mainLinkColor};;
text-decoration: underline;
&:hover {
color: ${props => props.theme.colors.textAccent};
text-decoration: underline;
}
`);
export const Link = <StyledLink as={RRLink} />;
这显然是行不通的...所以有没有办法让 Link 模仿 StyledLink 样式,但使用 "a" 标签而不是 "span" ?
只需从 styled-components
导入并使用 css
,如下所示:
import React from "react";
import ReactDOM from "react-dom";
import styled, { css } from 'styled-components';
const sharedStyles = css`
background-color: gold;
`;
const Div = styled.div`
${sharedStyles}
`;
const Button = styled.button`
${sharedStyles}
`;
const App = () => (
<>
<Div>Hello Div</Div>
<Button>Hello Button</Button>
</>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);