Files
defgov/packages/ui/src/common/Box.tsx
2026-03-24 18:22:47 +08:00

42 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;