简体   繁体   English

在带有flowtype的React中,我如何只键入某些道具并允许其他任何道具

[英]In React with flowtype how do I type only certain props and allow any others

I'm making an input in form and want to type certain props for my input component but allow any others through without typing them - like all the attributes for an input field. 我正在以形式进行输入,并希望为我的输入组件键入某些道具,但允许其他任何类型都输入而无需键入它们-就像输入字段的所有属性一样。

Do I really need to create a type for all of them? 我真的需要为所有这些对象创建一个类型吗?

Flow supports subtype polymorphism. 流支持亚型多态性。 So if you define a type like this 因此,如果您定义这样的类型

type Foo = {
  a: number,
  b: string,
}

Any object that has at least those fields, will be a valid Foo : 至少具有这些字段的任何对象都将是有效的Foo

let foo: Foo = { 
    a: 0,
    b: "hello",
    c: false // this is ok
}

However, if you actually need to access those fields then you should make them part of the type. 但是,如果您实际上需要访问这些字段,则应将它们作为类型的一部分。

You can define an intersection type of custom props + any input props: 您可以定义自定义道具+任何输入道具的交集类型:

type Props = {
  foo: string,
  bar: number,
} & $Shape<HTMLInputElement>

$Shape used above: $上面使用的形状

Copies the shape of the type supplied, but marks every field optional. 复制提供的类型的形状,但将每个字段都标记为可选。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何只允许具有特定权限的用户切换命令? - How do I only allow a command to be toggled by users with certain permissions? 在flowtype中细化“ any”类型 - Type refining an `any` type in flowtype 如何使用FlowType继承类? - How do I inherit class with FlowType? 如何只允许某些组件滚动并保持某些 React 组件固定? - How can I only allow certain components to scroll and keep certain React components fixed? 如何在流类型接口上对类的构造函数参数进行严格的类型检查? - How do I get strict type checking on flowtype interfaces to constructor arguments for classes? 如何在不破坏格式化程序的情况下为flowtype声明React组件的模块类型? - How to declare the module type of an react component for flowtype, without breaking the formatter? 我怎么允许 <img> 和<a>innerHTML的标签,但没有其他标签吗?</a> <a>(建立论坛)</a> - How do I allow <img> and <a> tags for innerHTML, but no others? (Making a forum) 我如何渲染作为带有附加道具的道具传入的反应组件? - How do i render a react component passed in as a props with additional props? 如何将道具传递到反应组件? - How do I pass props to a react component? TypeScript + React:如何键入一个“rest”道具,将道具的 rest 收集到 object 中,然后将它们传播到某个元素? - TypeScript + React: How do I type a `rest` props that collects the rest of the props into an object and later spread them to some element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM