All
PC硬件
经验记录
生活杂谈
日常踩坑
前端技术
测试
2022-09-15
前端技术
react
typescript
146
React高阶组件之注入和增强使用示例

注入参数

// 向组件注入primaryColor: 'pink'参数
interface WithThemeProps {
    primaryColor: string
}

export function withTheme<T>(WrappedComponent: React.ComponentType<T & WithThemeProps>) {
    // Try to create a nice displayName for React Dev Tools.
    const displayName = WrappedComponent.displayName || WrappedComponent.name || 'Component'

    // Creating the inner component. The calculated Props type here is the where the magic happens.
    const ComponentWithTheme = (props: Omit<T, keyof WithThemeProps>) => {
        // Fetch the props you want to inject. This could be done with context instead.
        const themeProps = {
            primaryColor: 'pink',
        }
        // props comes afterwards so the can override the default ones.
        return <WrappedComponent {...themeProps} {...(props as T)} />
    }

    ComponentWithTheme.displayName = `withTheme(${displayName})`

    return ComponentWithTheme
}

增强参数

// 给组件增加loading参数
interface EnchanceProps {
    loading: boolean
}

const enchanceLoading = <T extends {}>(WrappedComponent: React.ComponentType<T>) => {
    const ComponentWithLoading = (props: T & EnchanceProps) => {
        const { loading } = props

        return loading ? <div>loading.....</div> : <WrappedComponent {...props} />
    }

    return ComponentWithLoading
}

注入和增强使用

const A = (props: { a?: string } & WithThemeProps) => {
    return <div>{props.primaryColor}</div>
}

const AwithTheme = withTheme(A)

const LoadingA = enchanceLoading(AwithTheme)

const B = () => {
    return <LoadingA loading={true}></LoadingA>
}
Back
© 2022 BBF Powered byNext.js&Prisma&Tailwind.css