Reactjs 在函数上使用React FC
我想学习如何在React.js的正常函数中使用Reactjs 在函数上使用React FC,reactjs,typescript,function,react-props,Reactjs,Typescript,Function,React Props,我想学习如何在React.js的正常函数中使用React.FC 我知道有两种类型的功能;第一个是(我更喜欢的): 有人告诉我,如果我想在函数上使用React.FC,我应该这样做: const QuestionCard: React.FC<Props> = () => ( <div>Question Card</div> ); export default QuestionCard; 但是代码编辑器向我显示了如下错误: 在typescrip
React.FC
我知道有两种类型的功能;第一个是(我更喜欢的):
有人告诉我,如果我想在函数上使用React.FC
,我应该这样做:
const QuestionCard: React.FC<Props> = () => (
<div>Question Card</div>
);
export default QuestionCard;
但是代码编辑器向我显示了如下错误:
在typescript中,不能将类型别名应用于函数语句。仅限于分别键入参数和返回类型
function foo(arg1: Arg1Type, arg2: Arg2Type): MyReturnType {
//...
}
但如果您有函数类型别名,则必须改用此表单:
type MyFn = (arg1: Arg1Type, arg2: Arg2Type) => MyReturnType
const foo: MyFn = (arg1, arg2) => {
//...
}
这就是语法工作的方法。这意味着,如果要为功能组件使用React.FC
类型别名,则必须使用const MyComponent:React.FC
但是,(警告:从这里开始,这就成为了人们的看法)我想补充一点,您根本不需要
React.FC
。它实际上给了你一个额外的children?:React.ReactNode
prop,它无论如何都不希望出现在每个组件上。事实上,如果一个组件不允许子元素,并且您仍然向它传递了一些子元素,那么我将期望出现一个类型错误React.FC
并不能很容易地明确说明这一点
例如:
interface Props {
foo: string
}
// A React.FC declared component that should not take children.
const MyComponentC: React.FC<Props> = ({ foo }) => {
return <>{ foo }</>
}
const c = <MyComponentC foo='bar' /> // expected usage
const cWithChildren = <MyComponentC foo='bar'>some children</MyComponentC> // no type error
现在,子类的存在是由类型系统强制执行的,并且声明组件的语法在所有情况下都是干净和简单的
出于这些原因,我现在不推荐使用React.FC
不要使用
React.FC
。
function foo(arg1: Arg1Type, arg2: Arg2Type): MyReturnType {
//...
}
type MyFn = (arg1: Arg1Type, arg2: Arg2Type) => MyReturnType
const foo: MyFn = (arg1, arg2) => {
//...
}
interface Props {
foo: string
}
// A React.FC declared component that should not take children.
const MyComponentC: React.FC<Props> = ({ foo }) => {
return <>{ foo }</>
}
const c = <MyComponentC foo='bar' /> // expected usage
const cWithChildren = <MyComponentC foo='bar'>some children</MyComponentC> // no type error
// A function statement declared component that takes no children.
function MyComponentA({ foo }: Props) {
return <>Foo: {foo}</>
}
const a = <MyComponentA foo='bar' />
const aWithChildren = <MyComponentA foo='bar'>some children</MyComponentA> // type error
// A function statement declared component that DOES take children.
function MyComponentB({ foo, children }: PropsWithChildren) {
return <>
<p>Foo: {foo}</p>
<p>{children}</p>
</>
}
const b = <MyComponentB foo='bar' /> // type error
const bWithChildren = <MyComponentB foo='bar'>some children</MyComponentB>