Reactjs 是否为TypeScript定义非功能组件?
您可以使用以下命令在TypeScript中定义React功能组件的类型:Reactjs 是否为TypeScript定义非功能组件?,reactjs,typescript,Reactjs,Typescript,您可以使用以下命令在TypeScript中定义React功能组件的类型: export const Component: React.FC = () => { return // Stuff }; 如何对非箭头函数执行相同的操作 function Component() { return // Stuff } 练习有什么不同吗?这个流行的备忘单没有涵盖它,所以我想知道是否有理由不使用这种语法 当您使用const声明组件时,对某些特定情况有更好的类型支持。要了解这些情况,您可以查
export const Component: React.FC = () => {
return // Stuff
};
如何对非箭头函数执行相同的操作
function Component() {
return // Stuff
}
练习有什么不同吗?这个流行的备忘单没有涵盖它,所以我想知道是否有理由不使用这种语法
当您使用
const
声明组件时,对某些特定情况有更好的类型支持。要了解这些情况,您可以查看React.FC
类型:
type FC<P = {}> = FunctionComponent<P>;
interface FunctionComponent<P = {}> {
(props: PropsWithChildren<P>, context?: any): ReactElement | null;
propTypes?: WeakValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}
最后,同样的类型安全也可以通过函数
声明来实现,但它只需要更多的代码
如何对非箭头函数执行相同的操作
import*as React from'React';
函数nonatarrow():React.ReactElement{
返回(
非胖箭头函数
);
}
常量箭头:React.FunctionComponent=\u props=>{
返回(
);
};
练习有什么不同吗
除了React和Typescript之外,在ES6中,fat arrow函数捕获的内容很少,包括这个
,并且会随身携带捕获内容。因此,如果有数千个这样的函数,那么将有捕获的开销
回到React和Typescript,React.FunctionComponent中没有使用此,但是如果您选择的Typescript transpiler将文件传输到ES6,则将有带捕获的胖箭头函数
因此,这完全取决于所选的transpiler及其设置。使用Typescript编译器,如果在tsconfig.json中有
“target”:“es5”
,则FatArrow
组件将被传输到es5函数中。将设置更改为“target”:“es6”
确保FatArrow
被传输到arrow函数。使用Babel作为transpiler,您的里程数可能会有所不同。如果您想使用完整类型的函数来键入非箭头函数,您可以使用如下内容():
让我添加:(x:number,y:number)=>number=
函数(x:number,y:number):number{返回x+y;};
就你而言:
const MyComponent:React.FC=function(){
返回;
};
有用的解释:。由于Typescript的限制,您似乎丢失了类型信息:这并不能真正解决示例中nonatarrow
不是React.FC
的问题,因此您不会获得任何好处。试着在里面使用儿童道具,typescript就会抱怨
function FooAsFunc({ children }) { // children has 'any' type
return 1234
}
const FooAsConst: React.FC = ({ children }) => {
return 1234 // type error: typescript knows that 1234 is not valid react component return type
}
FooAsFunc.displayName = new Date()
FooAsConst.displayName = new Date() // type error: 'displayName' suppose to be of a type string