【问题标题】:How react can Identify it's a class component or functional component?react如何识别它是类组件还是功能组件?
【发布时间】:2020-02-27 19:41:59
【问题描述】:

我在我的 React App 中创建了两个组件,一个是类组件,另一个是功能组件。但是react如何识别它调用的组件是类组件还是函数式组件呢?

这是面试官提出的问题

【问题讨论】:

  • 简单的关键字搜索class?你/面试官到底想问什么?

标签: javascript reactjs class components


【解决方案1】:

但是react如何识别它调用的组件是类组件还是函数式组件呢?

// 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 represents objectsstated in docs 是等价的:

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

但是actually,React 检查isReactComponent flag 以确定它是类组件还是函数组件:

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

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

更深入的解释请查看Dan Abramov's blog post

【讨论】:

    【解决方案2】:

    React 检查组件中的 isReactComponent 标志(出现在 React.Component.prototype source 上)以确定它是类还是函数。

    你可以在这里详细阅读:https://overreacted.io/how-does-react-tell-a-class-from-a-function/

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      相关资源
      最近更新 更多