type DndBoxProps = React.PropsWithChildren<{
accepts?: any[];
// "all" | "left" | "right" | "top" | "bottom"
// 每个只能填一次,
// 如果 all 填了, 其他就不能存在
// 默认值 为 all
edge?: string[];
}>;
如何约束 prop 能传入多个值,但每个值限1次?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- 崽崽的谷雨 2023-04-20 08:51关注
引用自 chatGPT:
可以使用 TypeScript 中的联合类型和类型别名来实现这个需求。具体做法如下:1.定义一个类型别名来描述边缘类型列表,其中包含了所有可能的边缘类型,包括 "all"、"left"、"right"、"top" 和 "bottom":
type EdgeType = "all" | "left" | "right" | "top" | "bottom";
2.定义一个接口类型 DndBoxProps 来约束组件的 props,其中 edge 属性的类型为 EdgeType[]:
interface DndBoxProps { accepts?: any[]; edge?: EdgeType[]; children?: React.ReactNode; }
3.在调用组件的地方,可以像下面这样使用 DndBox 组件,并传入 edge 属性,每个属性只能传入一次,否则会报错。
import { DndBoxProps } from './DndBoxProps'; function App() { return ( <div> <DndBox accepts={['text']} edge={['all']} /> <DndBox accepts={['text', 'image']} edge={['left', 'right']} /> <DndBox accepts={['image']} edge={['top']} /> </div> ); }
这样,在使用 DndBox 组件时,就能够约束 edge 属性只能传入 "all"、"left"、"right"、"top" 和 "bottom" 中的任意一个,每个值只能传入一次。
解决 无用评论 打赏 举报
悬赏问题
- ¥20 测距传感器数据手册i2c
- ¥15 RPA正常跑,cmd输入cookies跑不出来
- ¥15 求帮我调试一下freefem代码
- ¥15 matlab代码解决,怎么运行
- ¥15 R语言Rstudio突然无法启动
- ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
- ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
- ¥15 用windows做服务的同志有吗
- ¥60 求一个简单的网页(标签-安全|关键词-上传)
- ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法