03.函数组件的代码实现
具体代码演化过程请观看视频,这里呈现关键代码:
js
// index.js
import React from './react';
import ReactDOM from './react-dom';
function MyFunctionComponent(props){
return <div className='test-class' style={{color: 'red'}}>Simple React App<span>{props.xx}</span><span>xx2</span></div>
}
ReactDOM.render(<MyFunctionComponent xx="xx1"/>, document.getElementById('root'))js
// react-dom.js
function createDOM(VNode){
const {type, props} = VNode
let dom;
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 getDomByFunctionComponent(vNode) {
let { type, props } = vNode;
let renderVNode = type(props);
if (!renderVNode) return null;
return createDOM(renderVNode);
}