简体   繁体   English

Function 作为 React.js + TypeScript 组件中的属性

[英]Function as property in React.js + TypeScript component

What are the differences between this syntax?这种语法有什么区别? What types will they have?他们会有哪些类型?

eg:例如:

const foo = () => (<>Something...</>);  

const bar = (arg: string) => (<>{arg}</>);

interface IComponent {
property: ???
}

<Component property={foo} />
<Component property={foo()} />
<Component property={() => foo} />
<Component property={() => foo()} />
<Component property={() => bar(arg)} />
<Component property={bar(arg)} />

When you are trying to set a React Component as a property you should go with ReactElement or ReactNode .当您尝试将 React 组件设置为属性时,您应该使用ReactElementReactNode These types can be imported by the react component.这些类型可以由react组件导入。

Also then only your first definition is valid.那么只有你的第一个定义是有效的。 (Okay Maybe second and last one too, but that is not what you really want. (好吧,也许第二个也是最后一个,但这不是你真正想要的。

Your result:你的结果:

property: ReactElement

Definition 3 is function that returns a function, so the valid syntax should be:定义 3 是 function,它返回一个 function,所以有效的语法应该是:

property: () => () => ReactElement<{args: string}>

Definition four and five is a simpler for.定义四和五是比较简单的。 It directly returns a React Node:它直接返回一个 React 节点:

property: () => ReactElement or property: () => ReactElement
property: () => ReactElement<{args: string}>

It depends how your component should look like:)这取决于您的组件的外观:)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM