如何使用 Styled Components 以相同的样式扩展 Link 和 NavLink

How to extend Link and NavLink with same styles using Styled Components

样式化组件的新手,我正在尝试寻找一种更好的方式来扩展和共享样式。

我有类似的东西:

import styled from 'styled-components'
import { Link, NavLink } from 'react-router-dom';

const StyledNavLink = styled(Link)`
  position: relative;
  display: flex;
  height: 100%;
  text-decoration: none;
`;

const StyledNavLink = styled(NavLink)`
  position: relative;
  display: flex;
  height: 100%;
  text-decoration: none;
`;

有没有办法为两个组件定义相同的属性一次?

编辑:我想我有一个方法(使用css helper function

import styled, {css} from 'styled-components'
import { Link, NavLink } from 'react-router-dom';

const sharedStyle = css`
  position: relative;
  display: flex;
  height: 100%;
  text-decoration: none;
`

const StyledNavLink = styled(Link)`
  ${sharedStyle}
`;

const StyledNavLink = styled(NavLink)`
  ${sharedStyle}
`;

一种方式是您的回答方式:

import styled, {css} from 'styled-components'
import { Link, NavLink } from 'react-router-dom';

const sharedStyle = css`
  position: relative;
  display: flex;
  height: 100%;
  text-decoration: none;
`

const StyledNavLink = styled(Link)`
  ${sharedStyle}
`;

const StyledNavLink = styled(NavLink)`
  ${sharedStyle}
`;

另一个可能是创建一个专用函数:

import styled, {css} from 'styled-components'
import { Link, NavLink } from 'react-router-dom';

const withLinkStyles = (component) => styled(component)`
  position: relative;
  display: flex;
  height: 100%;
  text-decoration: none;
`;

const StyledNavLink = withLinkStyles(Link);
const StyledNavLink = withLinkStyles(NavLink);

我会选择第一个,因为它看起来更具表现力,并且符合 styled-components 作者打算使用该库的声明方式。