我正在尝试使用 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
。
我该如何解决这个问题?
最佳答案
我认为您导入的 MUButton 错误。应该<Button />
组件实际上是<MUButton />
?
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>
}
编辑:按照安迪在评论中提到的那样传递 className 属性
关于javascript - 如何使用从已有样式组件扩展的样式组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59757842/