首页 > 解决方案 > 有没有办法用不同的主要元素声明样式化的组件?

问题描述

我需要创建 2 个类似样式的组件,它们将共享它们的样式但使用不同的 HTML 元素。

有一种在运行时使用“as”属性()的方法,但我有一个特定的导出,我需要使用默认值,但我需要它以某种方式不使用它,因此链接样式的组件是“ styled.a" 和 StyledLink 组件为 "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} />;

这显然是行不通的......那么有没有办法让链接模仿 StyledLink 样式但使用“a”标签而不是“span”?

标签: reactjsstyled-components

解决方案


只需像这样导入和css使用styled-components

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);


推荐阅读