样式组件,使用gatsby-link锚标记css着色

时间:2018-04-03 20:56:48

标签: html css reactjs styled-components gatsby

我正在尝试使用<Link/>包格式化gatsby-link包中的styled-components组件通常我只需创建一个const给它Name设置相同以styled.a为例,写下我的CSS。但是,当我为const创建<Link/>时,出现Duplicate declaration "Link"错误。如何使用<Link>styled-components组件添加样式。

这是我的代码

import React from 'react';
import Link from 'gatsby-link';
import styled from "styled-components";

const Header = styled.div`
  margin: 3rem auto;
  max-width: 600px;
  background:red;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
`;

const Title = styled.h1`
  color: aqua;
`;

const Link = styled.a`
  color: aqua;
`;


export default () => (
  <Header>
        <Title>
          <Link to="/">
            Gatsby
          </Link>
        </Title>
  </Header>
);

2 个答案:

答案 0 :(得分:14)

您应该可以执行以下操作:

import { Link } from 'gatsby';

const StyledLink = styled(props => <Link {...props} />)`
  color: aqua;
`;

// ...

<StyledLink to="/">
  Gatsby
</StyledLink>

过期版本(gatsby v1,styled-components v3):

import Link from 'gatsby-link';

const StyledLink = styled(Link)`
  color: aqua;
`;

// ...

<StyledLink to="/">
  Gatsby
</StyledLink>

答案 1 :(得分:3)

重命名Link导入。

import { Link as GatsbyLink } from "gatsby";

如果您为组件Link命名,则可能会遇到命名冲突,因为该名称在不同框架中无处不在。您描述的错误指出您有多个具有相同名称的组件。

显式命名组件(改编自@Fabian Schultz的答案):

import { Link as GatsbyLink } from "gatsby";

const StyledLink = styled(GatsbyLink)`
  color: aqua;
`;

// ...

<StyledLink to="/">
  Gatsby
</StyledLink>
相关问题