如何扩展导入的零部件样式的零部件



我无法扩展导入的组件。我查看了样式组件文档,发现在v4+中应该可以使用prop"as",但事实并非如此。

组件:

type Props = {
padding: string,
justify: string
}
const FlexContainer = styled.div<Props>`
padding: ${props => props.padding};
display: flex;
flex-wrap: wrap;
justify-content: ${props => props.justify};
`
export const Flexcontainer: React.FC<Props> = props =>{
return (
<FlexContainer padding={props.padding} justify={props.justify}>
{props.children}
</FlexContainer>

)
}

扩展风格:

import { Flexcontainer }  from '../../reusable/FlexContainer';
const FlexContainerExtended = styled.div`
color: red;
`

使用:

<FlexContainerExtended
padding={null}
justify={"flex-start"}
as={Flexcontainer}>

您只需要在Flexcontainer组件中添加一个道具className,如下所示:

export const Flexcontainer: React.FC<Props> = props =>{
return (
<FlexContainer className={props.className} padding={props.padding} justify={props.justify} >
{props.children}
</FlexContainer>
)}

为了覆盖样式,样式化组件将className作为道具传递给被覆盖的组件,这就是的原因

您只需将基本组件传递给样式化的函数即可覆盖它。

type Props = {
padding: string,
justify: string
}
const FlexContainer = styled.div<Props>`
padding: ${props => props.padding};
display: flex;
flex-wrap: wrap;
justify-content: ${props => props.justify};
`
const FlexContainerExtended = styled(FlexContainer)`
color: red;
`
export const Flexcontainer: React.FC<Props> = props =>{
return (
<FlexContainer padding={props.padding} justify={props.justify}>
{props.children}
</FlexContainer>
)
}
// And use it like this
<FlexContainerExtended
padding={null}
justify={"flex-start"}/>

我知道这个问题很久以前就被问过了,但我把我找到的解决方案留给了未来的访客。

基本组件定义

import React from 'react'
import styled from 'styled-components'
const ContainerWrapper = styled.div`
width: 100%;
max-width: 1200px;
padding-left: 5%;
padding-right: 5%;
margin-left: auto;
margin-right: auto;
`
export default function Container({ children, ...props }) {
return (
<ContainerWrapper {...props}>
{children}
</ContainerWrapper>
)
}

扩展组件定义

Obs.:请注意,扩展组件是一个article,而基本组件是div,到目前为止它们没有关系。

还要注意,基本组件(Container(已导入,但尚未使用。

import React from 'react'
import styled from 'styled-components'
import Container from '../../common/Container'
const HeroWrapper = styled.article`
height: 100vh;
padding-top: 74px;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
background-attachment: fixed;
`

调用组件

现在,在我声明扩展组件的同一个文件中,我只调用基本组件,在as属性中通知扩展组件的名称。

export default function PostsWrapper() {
return (
<Container as={HeroWrapper}>
{/* ...  */}
</Container>
)
}

最新更新