【问题标题】:What's the difference between a React.FunctionComponent and a plain JS function component?React.FunctionComponent 和普通的 JS 函数组件有什么区别?
【发布时间】:2019-05-24 22:46:27
【问题描述】:

这两个例子完成了同样的事情。但是引擎盖下有什么区别?我了解功能组件与 React.Component 和 React.PureComponent,但我一直无法找到有关 React.FunctionComponent 的相关文档。

React.FunctionComponent

const MyComponentA: React.FunctionComponent = (props) => {
  return (
    <p>I am a React.FunctionComponent</p>
  );
};

纯JS函数组件:

const MyComponentB = (props) => {
  return (
    <p>I am a plain JS function component</p>
  );
};

【问题讨论】:

  • 很确定它们完全一样,但一个是 TypeScript,另一个是 JavaScript。
  • 一个是TypeScript + JSX,另一个就是JSX。

标签: javascript reactjs typescript


【解决方案1】:

引擎盖下没有区别。第一个是使用TypeScript语法来表示React.FunctionComponent的类型,但它们都是纯JS函数组件。

【讨论】:

  • 有一些细微差别,普通函数组件可以返回字符串,如:``` const FooString = () => "foo"; ``` 但你不能从 FunctionComponent 返回字符串。 ``` const BarString: React.FC = () => "string"; ``` 因此返回类型必须是 ReactElement|null
  • 那不是真的。在底层 FunctionComponent 至少有 children 属性,而在你的 playin JS 函数组件中你必须定义它。
【解决方案2】:

有一些细微差别,普通函数组件可以返回字符串,如:

const FooString = () => "foo";

但您无法从 FunctionComponent 返回字符串。

const BarString: React.FC<{}> = () => "string";

因此返回类型必须是ReactElement|null

【讨论】:

  • 我是 TS 新手,有谁知道这是为什么?
  • @JoelMellon 在第一个代码示例中,TypeScript 会将该函数视为任何普通函数,并且可以从中“看到”它返回一个 string,这一切都很好。在 section 示例中,我们告诉 TS 函数是 React.FC(定义为返回 ReactElement|null),但是因为编译器看到返回了字符串,所以会生成警告。
  • 哦,知道了。这很有意义。我并没有真正认为React.FunctionComponent 是一个类,我们实际上是在对函数的返回值进行类型提示。 10/10 谢谢,朋友。
【解决方案3】:

不同的是FunctionComponent默认自带一个属性:children


// Note, no children defined
type Props = {
  name: string
}

const MyComponentA: React.FunctionComponent<Props> = (props) => {
  return (
    <p>I am a React.FunctionComponent and my name is {props.name}</p>
    <p>And I have {props.children}</p>
  );
};

const MyComponentB = (props: Props) => {
  return (
    <p>I am a plain JS function component</p>
    <p>But my {props.children} are undefined</p>
  );
};

对于MyComponentB,TS 编译器会抱怨children 没有定义。

当然,对于这两个组件,您可以只传递子组件并忽略 TS 警告。

【讨论】:

  • React 在这两种情况下 props.children 都有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
  • 2020-09-22
  • 1970-01-01
相关资源
最近更新 更多