reactjs 在React中,如何约束prop每个值只传递一次

ycggw6v2  于 2023-04-29  发布在  React
关注(0)|答案(2)|浏览(129)
type DndBoxProps = React.PropsWithChildren<{
  accepts?: any[];
  // "all" 
  // "left" | "right" | "top" | "bottom"
  edge?: string[];
}>

如果我传递'all',那么就不能传递'top','right','left','bottom'。

x6h2sr28

x6h2sr281#

您可以使用区分并添加自定义类型

type EdgeType = 'all' | 'left' | 'right' | 'top' | 'bottom';

type Edge =
    | { edges: ['all'] }
    | { edges: Exclude<EdgeType, 'all'>[] }

type DndBoxProps = React.PropsWithChildren<{
    accepts?: any[];
    edgeConfig?: Edge;
}>;

export function DndBox(props: DndBoxProps) {
    return (
        <>
            {props.edgeConfig?.edges.map((edge) => {
                return <h3>{edge}</h3>
            })}
        </>
    )
}

这样<DndBox edgeConfig={{edges: ['all', 'left']}} />-将引发错误

pgky5nke

pgky5nke2#

感谢您的回复!我认为你的这个解决方案不够好。

edges={{edges:['bottom','bottom']} will silence

这和你的答案有相同的检查

type E =  "left" | "right" | "top" |  "bottom"

type DndBoxProps = React.PropsWithChildren<{
  accepts?: any[];

  edge?: ["all"] | E[] ;
}>;

我现在把它改成了

type DndBoxProps = React.PropsWithChildren<{
  accepts?: any[];
  top?: boolean;
  right?: boolean;
  bottom?: boolean;
  left?: boolean;
  
}>;

相关问题