[英]How react can Identify it's a class component or functional component?
I have created two component in my React App one is class component and another one is functional component.我在我的 React App 中创建了两个组件,一个是 class 组件,另一个是功能组件。 But how react can identify when it call the component it's a class component or functional component?
但是当它调用组件时,react 如何识别它是 class 组件还是功能组件?
It's a question ask by Interviewer这是面试官提出的问题
But how react can identify when it calls the component it's a class component or functional component?
但是当它调用组件时,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')
);
While JSX represents objects , as stated in docs they are equivalent:虽然JSX 代表 objects ,如文档中所述,它们是等价的:
The above two components are equivalent from React's point of view.
从 React 的角度来看,上述两个组件是等价的。
But actually , React checking isReactComponent
flag to determinate if it's a class component or function component:但实际上,React 检查
isReactComponent
标志以确定它是 class 组件还是 function 组件:
// @ ReactComponent.js
ReactComponent.prototype.isReactComponent = {};
// @ ReactFiber.js
function shouldConstruct(Component: Function) {
const prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
For more in-depth explanation check Dan Abramov's blog post .有关更深入的解释,请查看Dan Abramov 的博客文章。
React check the component for the isReactComponent
flag (which is present on React.Component.prototype
source ) to determine weather it's a class or a function. React 检查组件的
isReactComponent
标志(存在于React.Component.prototype
源上)以确定天气它是 class 还是 function。
You can read about it in detail here: https://overreacted.io/how-does-react-tell-a-class-from-a-function/您可以在此处详细了解它: https://overreacted.io/how-does-react-tell-a-class-from-a-function/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.