【问题标题】:How to use styled-components that extends from an already styled component?如何使用从已经样式化的组件扩展而来的样式化组件?
【发布时间】:2020-05-02 14:23:22
【问题描述】:

我正在尝试使用 styled-component 将我的所有组件样式提取到单个文件中。

但是,我遇到了一个错误,如果我将样式和样式所依赖的组件提取到单独的文件中,主题将停止工作。

Button.jsx

import {ButtonWrapper} from './Button.styled';
import {Button as MUButton} from '@material-ui/core/Button';

export const Button = () => {
  return <ButtonWrapper>
    <Button/>
  </ButtonWrapper>
}

SmallButton.jsx

import {StyledSmallButton} from './Button.styled';

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

// const StyledSmallButton = styled(Button)` // This works.
//   width: 50%
// `

export const SmallButton = () => {
  return <StyledSmallButton/>
}

Button.styled.jsx

import {Button} from './Button';

export const ButtonWrapper = styled.div`
  width: 100%
`;

export const StyledSmallButton = styled(Button)` //Doesn't work.
  width: 50%
`;

错误

Uncaught Error: Cannot create styled-component for component: undefined

我认为这里存在循环依赖问题,即SmallButton 需要以ButtonWrapper 为主题的Button。 我该如何解决这个问题?

【问题讨论】:

  • 另外,请注意,在重新设置样式组件时,请务必将 className 作为道具传递,否则您的样式将不起作用

标签: javascript css reactjs styled-components


【解决方案1】:

我认为您错误地导入了 MUButton。 &lt;Button /&gt; 组件实际上应该是 &lt;MUButton /&gt; 吗?

import {ButtonWrapper} from './Button.styled';
import {Button as MUButton} from '@material-ui/core/Button';
                 // ^ this is the alias

export const Button = ({ className }) => {
  return <ButtonWrapper>
    <MUButton className={className} />
     // ^ This should be MUButton
  </ButtonWrapper>
}

编辑:如 Andy int he cmets 所述,将 className 属性向下传递

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 2020-04-01
    • 2019-03-25
    • 2020-09-26
    • 2020-09-22
    • 1970-01-01
    • 2021-07-02
    • 2020-10-27
    • 2021-11-01
    相关资源
    最近更新 更多