04.类组件的基本实现
其实在日常开发中,我们已经很少用类组件的形式来编写代码,但是,类组件会长期存在,我们有必要在这里去进行研究,而且有了对类组件的理解,有助于我们后续对Hooks的相关内容进行深入的掌握
具体代码演化过程请观看视频,这里呈现关键代码:
js
// Component.js
export class Component {
static IS_CLASS_COMPONENT = true
constructor(props) {
this.props = props;
}
}js
//react-dom.js
function createDOM(VNode){
const {type, props} = VNode
let dom;
if (typeof type === 'function' && type.IS_CLASS_COMPONENT && VNode.$$typeof === REACT_ELEMENT){
return getDomByClassComponent(VNode)
} else if (typeof type === 'function' && VNode.$$typeof === REACT_ELEMENT){
return getDomByFunctionComponent(VNode)
} else if (type && VNode.$$typeof === REACT_ELEMENT) {
dom = document.createElement(type);
}
if(props){
if (typeof props.children === 'object' && props.children.type) {
mount(props.children, dom)
} else if (Array.isArray(props.children)) {
mountArray(props.children, dom);
} else if (typeof props.children === 'string'){
dom.appendChild(document.createTextNode(props.children));
}
}
setPropsForDOM(dom, props)
return dom
}
function getDomByClassComponent(vNode){
let { type, props } = vNode;
let instance = new type(props)
let renderVNode = instance.render();
if (!renderVNode) return null;
return createDOM(renderVNode);
}