React.FunctionComponent和普通的JS函数组件之间有什么区别?

时间:2018-12-26 18:57:11

标签: javascript reactjs

这两个示例完成相同的操作。但是幕后的区别是什么?我了解功能组件与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>
  );
};

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:4)

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

const FooString = () => "foo";

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

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

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

答案 2 :(得分:1)

区别在于DjangoTemplates默认带有一个属性: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> ); }; ,TS编译器会抱怨MyComponentB未定义。

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

相关问题