gpt4 book ai didi

reactjs - 在函数上使用 React FC

转载 作者:行者123 更新时间:2023-12-05 02:42:37 29 4
gpt4 key购买 nike

我想学习如何使用React.FC<>在 react.js 的正常功能中。

我知道有两种类型的函数;第一个是(我更喜欢的那个):

  function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

另一个是这样的:

const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
"& > * + *": {
marginLeft: theme.spacing(2),
},
},
})
);

有人告诉我,如果我想使用 React.FC<>在功能上我应该这样做:

const QuestionCard: React.FC<Props>  = () => (
<div>Question Card</div>
);

export default QuestionCard;

但我不想用 const functions 来做(如果那是它的名字)。我想用正常的功能来做。我试过这样:

export default function QuestionCard : React.FC<Props>() {

//duda
return <div>Question Card</div>;
}

但是代码编辑器显示如下错误: error image

最佳答案

在 typescript 中,您不能将类型别名应用于函数语句。您只能分别输入参数和返回类型。

function foo(arg1: Arg1Type, arg2: Arg2Type): MyReturnType {
//...
}

但是如果你有一个函数类型别名,你必须改用这种形式:

type MyFn = (arg1: Arg1Type, arg2: Arg2Type) => MyReturnType
const foo: MyFn = (arg1, arg2) => {
//...
}

这就是语法的工作方式。这意味着如果你想使用 React.FC<Props>为您的功能组件键入别名,那么您必须使用 const MyComponent: React.FC<Props>


但是,(警告:从这里开始,这变成了一种观点)我想补充一点,你并不真的需要 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 的例子而是声明 children明确。

// 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>

现在子项的存在由类型系统强制执行,并且声明组件的语法在所有情况下都简洁明了。

出于这些原因,我真的不建议使用 React.FC这些天。

Typescript playground with above example

关于reactjs - 在函数上使用 React FC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67422983/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com