I have created two component in my React App one is class component and another one is functional component. But how react can identify when it call the component it's a class component or functional component?
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?
// 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:
The above two components are equivalent from React's point of view.
But actually , React checking isReactComponent
flag to determinate if it's a class component or function component:
// @ 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 .
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.
You can read about it in detail here: https://overreacted.io/how-does-react-tell-a-class-from-a-function/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.