javascript - 样式组件导入结果未定义

标签 javascript reactjs styled-components

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

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

StyledComponents.jsx

import styled from 'styled-components';

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

应用程序.jsx

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

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

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

横幅.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 也是可以的,但是你可以自由地做任何你想做的事情!

关于javascript - 样式组件导入结果未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54432492/

相关文章:

reactjs - 样式化组件,定义为 defaultProps 的必需 Prop 显示为缺失

Javascript - "concatenate"在 for 循环中有一个变量

javascript - AngularJS。按数组过滤数组

javascript - 数组转换树结构

reactjs - 链接内的 React-router 可点击元素

javascript - 根据 window.pageYOffset 更改样式组件样式

javascript - 从firebase javascript获取值(value)后运行一些东西

reactjs - 文件中的两个 useContext

javascript - React.createElement 类型无效/未捕获错误 : element type is invalid - Error related to require(COMPONENT) in babel v7 (@babel/core)

reactjs - 无法使用 @emotion/styled 访问样式组件中的主题