样式组件导入结果未定义

styled-component import results in undefined

我刚刚进入 styled-components 并且遇到了一些问题。我正在尝试通过不同的文件扩展 button 并且出于某种原因它导入为 undefined

这个错误最初出现在 NavLink 组件中,导致人们认为它可能是一个反应问题,但它也发生在 styled.a``; 中,所以我认为不是这样。

StyledComponents.jsx

import styled from 'styled-components';

export const Button = styled.a`
  // general styling
`;

App.jsx

import { Button } from './StyledComponents/StyledComponents';

console.log(Button); // this works fine

export const MainButton = styled(Button)`
  // a little color and other styles
`;

Banner.jsx

import { MainButton } from '../App';

console.log(MainButton); // returns undefined

// if I omit the console logging above, this gives error of undefined
const _MainButton = styled(MainButton)`
  // specific styles for this component
`;

我不太确定发生了什么。我也不确定这是否是对这些样式组件进行分层的正确方法。如果有人可以分享一些见解,将不胜感激!

好吧,这个出口卷积就是问题所在。您正在将一个按钮从 StyledComponents.jsx 导入到 App.jsx,然后导出为 MainButton,然后再次导入到 Banner.jsx,它在 LandingPage 中呈现],它在 App.jsx 中呈现。呼。我通过移动 MainButton 定义并导出到另一个文件来解决这个问题。我不确定为什么,但事实就是如此。将样式化的组件保存在专用文件中是个好主意!例如,将 MainButton 移动到不同的文件:

/StyledComponents/StyledComponents.jsx

export const MainButton = styled(Button)`
    //styles go here
`;

然后更改导入:

Banner.jsx

import { MainButton } from '../StyledComponents/StyledComponents';

工作正常!

不过,一般来说,如果您想使用样式化组件对内容进行分层,我喜欢将其保存在一个文件中。如果您不需要全部导出,则不必全部导出,但您也可以:

const TitleBase = styled.h1`
  text-transform:uppercase;
  font-size: 1rem;
`;

export const GreenTitle = styled(Title)`
  color: green;
`;

export const RedTitle = styled(Title)`
  color:red;
`;

只要确保它们是有序的。您不能在 RedTitle 之后定义 Title,例如

一个小提示:使用 .js 扩展名代替 .jsx 也可以,但是您可以随意做任何您想做的事!