注入参数
interface WithThemeProps {
primaryColor: string
}
export function withTheme<T>(WrappedComponent: React.ComponentType<T & WithThemeProps>) {
const displayName = WrappedComponent.displayName || WrappedComponent.name || 'Component'
const ComponentWithTheme = (props: Omit<T, keyof WithThemeProps>) => {
const themeProps = {
primaryColor: 'pink',
}
return <WrappedComponent {...themeProps} {...(props as T)} />
}
ComponentWithTheme.displayName = `withTheme(${displayName})`
return ComponentWithTheme
}
增强参数
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>
}