gpt4 book ai didi

javascript - react 如何识别它是类组件还是功能组件?

转载 作者:行者123 更新时间:2023-11-30 13:49:05 26 4
gpt4 key购买 nike

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

面试官问的问题

最佳答案

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')
);

同时 JSX represents objects , 作为 stated in docs它们是等价的:

The above two components are equivalent from React’s point of view.

但是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 .

关于javascript - react 如何识别它是类组件还是功能组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58660414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com