繁体   English   中英

如何反应才能识别它是 class 组件还是功能组件?

[英]How react can Identify it's a class component or functional component?

我在我的 React App 中创建了两个组件,一个是 class 组件,另一个是功能组件。 但是当它调用组件时,react 如何识别它是 class 组件还是功能组件?

这是面试官提出的问题

但是当它调用组件时,react 如何识别它是 class 组件还是功能组件?

// Who is a class component and who is a functional component?
ReactDOM.render(
  <>
    <ComponentA />
    <ComponentB />
    {React.createElement(ComponentA)}
    {React.createElement(ComponentB)}
  </>,
  document.getElementById('root')
);

虽然JSX 代表 objects ,如文档中所述,它们是等价的:

从 React 的角度来看,上述两个组件是等价的。

实际上,React 检查isReactComponent标志以确定它是 class 组件还是 function 组件:

// @ ReactComponent.js
ReactComponent.prototype.isReactComponent = {};

// @ ReactFiber.js
function shouldConstruct(Component: Function) {
  const prototype = Component.prototype;
  return !!(prototype && prototype.isReactComponent);
}

有关更深入的解释,请查看Dan Abramov 的博客文章

React 检查组件的isReactComponent标志(存在于React.Component.prototype 上)以确定天气它是 class 还是 function。

您可以在此处详细了解它: https://overreacted.io/how-does-react-tell-a-class-from-a-function/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM