React.FunctionComponent接口使用疑问:函数组件写法为何报错?
React.FunctionComponent 两种写法报错原因解析
先看第一种合法的组件定义方式:
const Box: React.FunctionComponent = ({ children }) => ( <div> {children} </div> );
这里是类型注解:给变量Box指定类型为React.FunctionComponent(可简写为React.FC),这个接口会自动为组件props注入children属性,语法完全合规。
你写的第二种写法存在语法逻辑错误:
function Box2<React.FunctionComponent> ({ children }){ return ( <div> {children} </div> )}
报错提示Unexpected token, expected ",",核心问题是误用了TypeScript泛型语法:
- 函数名后的
<>是用来声明泛型类型变量的位置(比如<T>这种占位符),不是用来指定函数本身的类型。你直接把React.FunctionComponent这个具体接口放进泛型声明位,TypeScript无法解析这种非法语法,因此抛出错误。
正确的函数声明式组件写法
如果想用函数声明形式定义组件,有两种正确方式:
- 给props参数指定对应类型:
function Box2({ children }: React.FunctionComponent['props']) { return ( <div> {children} </div> ); }
- 给整个函数指定
React.FunctionComponent类型:
const Box2: React.FunctionComponent = function({ children }) { return ( <div> {children} </div> ); }
本质都是给组件函数指定正确的类型约束,而非错误地将类型塞进泛型声明位置。
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

