我正在尝试使用<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>
);
答案 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>