Typescript 无状态 React 组件作为命名函数
Typescript Stateless React Component as named function
假设我有一个名为 Link:
的 React 组件
function Link(props) {
return <a href={props.url}>{props.children}</a>
}
如何在不将其转换为箭头函数的情况下键入此函数?
这似乎不起作用:
interface ILink {
url: string
}
function Link(props: React.FC<ILink>) { }
// Property 'url' does not exist on type 'FC<ILink>'.
// Property 'children' does not exist on type 'FC<ILink>'.
但是作为箭头函数,它立即起作用了吗?
interface ILink {
url: string
}
const Link: React.FC<ILink> = (props) => { }
// Compiles
您必须使用 React.PropsWithChildren
和 React.ReactElement
组合,所以它变成:
function Link(props: PropsWithChildren<ILink>): ReactElement {}
假设我有一个名为 Link:
的 React 组件function Link(props) {
return <a href={props.url}>{props.children}</a>
}
如何在不将其转换为箭头函数的情况下键入此函数?
这似乎不起作用:
interface ILink {
url: string
}
function Link(props: React.FC<ILink>) { }
// Property 'url' does not exist on type 'FC<ILink>'.
// Property 'children' does not exist on type 'FC<ILink>'.
但是作为箭头函数,它立即起作用了吗?
interface ILink {
url: string
}
const Link: React.FC<ILink> = (props) => { }
// Compiles
您必须使用 React.PropsWithChildren
和 React.ReactElement
组合,所以它变成:
function Link(props: PropsWithChildren<ILink>): ReactElement {}