42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
import React from "react";
|
||
import { cn } from "tailwind-variants";
|
||
import type { CommonProps } from "@/common/CommonProps";
|
||
|
||
// 别名<约束>=值
|
||
// 千万不要 C = As extend React.ElementType,这样子连等号,会切断推导
|
||
type AsProp<C extends React.ElementType> = { as?: C };
|
||
|
||
type PropsToOmit<C extends React.ElementType, P> = keyof (AsProp<C> & P);
|
||
|
||
export type PolymorphicProps<C extends React.ElementType, P = {}> = (P &
|
||
AsProp<C>) &
|
||
Omit<React.ComponentPropsWithRef<C>, PropsToOmit<C, P>>;
|
||
|
||
interface BoxProps<C extends React.ElementType> extends CommonProps {
|
||
as?: C;
|
||
}
|
||
|
||
const Box = <C extends React.ElementType = "div">(
|
||
props: PolymorphicProps<C, BoxProps<C>>,
|
||
ref?: React.ComponentPropsWithRef<C>["ref"],
|
||
) => {
|
||
const { as: Component = "div", children, className, ...rest } = props;
|
||
|
||
|
||
const boxRootClass = cn( className);
|
||
|
||
return (
|
||
<Component ref={ref} className={boxRootClass} {...(rest as any)}>
|
||
{children}
|
||
</Component>
|
||
);
|
||
};
|
||
|
||
export type BoxComponent = <C extends React.ElementType = "div">(
|
||
props: PolymorphicProps<C, BoxProps<C>> & {
|
||
ref?: React.ComponentPropsWithRef<C>["ref"];
|
||
},
|
||
) => React.ReactElement | null;
|
||
|
||
export default Box as BoxComponent;
|