简体   繁体   English

如何使用样式化组件以相同的样式扩展Link和NavLink

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

New to Styled Components and I'm trying to figure out a better way to extend and share styles. 我是样式组件的新手,我正在尝试寻找一种更好的方式来扩展和共享样式。

I have something like: 我有类似的东西:

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

Is there a way to define the same proper only once for both components? 有没有办法为两个组件都定义一次相同的属性?

EDIT: I think I have one way to do it (using css helper function ) 编辑:我想我有一种方法(使用css helper函数

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}
`;

One way is the way from your answer: 一种方法是从答案中得出的方法:

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}
`;

The other could be to create a dedicated function: 另一个可能是创建专用功能:

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

I would choose the first one, as it seems more expressive and in-line with the declarative way styled-components authors intended the library to be used. 我选择第一个,因为它似乎更具表达力,并且与styled-components作者希望使用的声明性方式保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM