【发布时间】:2020-02-27 19:41:59
【问题描述】:
我在我的 React App 中创建了两个组件,一个是类组件,另一个是功能组件。但是react如何识别它调用的组件是类组件还是函数式组件呢?
这是面试官提出的问题
【问题讨论】:
-
简单的关键字搜索
class?你/面试官到底想问什么?
标签: javascript reactjs class components
我在我的 React App 中创建了两个组件,一个是类组件,另一个是功能组件。但是react如何识别它调用的组件是类组件还是函数式组件呢?
这是面试官提出的问题
【问题讨论】:
class?你/面试官到底想问什么?
标签: javascript reactjs class components
但是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 objects 和stated 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。
【讨论】:
React 检查组件中的 isReactComponent 标志(出现在 React.Component.prototype source 上)以确定它是类还是函数。
你可以在这里详细阅读:https://overreacted.io/how-does-react-tell-a-class-from-a-function/
【讨论】: