参考:手写简易前端框架:function 和 class 组件 - 掘金
一、function组件实现
// 这个封装成函数,然后传入参数 list 就是组件了
const list = ['aaa', 'bbb'];
const oneTimeElement = <ul className="list">
{
list.map(item => <li className="item">{item}</li>)
}
</ul>
// render(oneTimeElement, document.getElementById('root'));
// 封装抽象组件
function List(props) {
return (
<ul className="list">
{
props.list.map(item => <li className="item">{item}</li>)
}
</ul>
)
}
// render(<List list={list} />, document.getElementById('root'));
判断vdom为组件,则执行函数:
function isComponentVdom(vdom) {
return typeof vdom.type == 'function';
}
if (isComponentVdom(vdom)) {
const functionProps = vdom.props
const componentVdom = vdom.type(functionProps);
return render(componentVdom, parent);
}
二、class组件
function isComponentVdom(vdom) {
return typeof vdom.type == 'function'; // 函数和类class typeof 返回都是function
}
if (isComponentVdom(vdom)) {
const functionProps = vdom.props;
if (Component.isPrototypeOf(vdom.type)) { // 判断vdom是否为类,使用proto原型方法
const instance = new vdom.type(functionProps);
instance.componentWillMount();
const componentVdom = instance.render();
instance.dom = render(componentVdom, parent);
instance.componentDidMount();
return instance.dom;
} else {
const componentVdom = vdom.type(functionProps);
return render(componentVdom, parent);
}
}
/* class 组件需要声明一个类,有 state 的属性 */
class Component {
constructor(props) {
this.props = props || {};
this.state = null;
}
setState(nextState) {
this.state = nextState;
}
componentWillMount() {
return undefined;
}
componentDidMount() {
return undefined;
}
}
// class List extends Component {}