fake React, render() #1
by city41
HTML
<div id="root1">
</div>
JavaScript
class FeactDOMComponent {
constructor(element) {
this._element = element;
}
mountComponent(container) {
const domElement = document.createElement(this._element.type);
const textNode = document.createTextNode(this._element.props.children);
domElement.appendChild(textNode);
container.appendChild(domElement);
this._hostNode = domElement;
return domElement;
}
}
class FeactCompositeComponentWrapper {
constructor(element) {
this._element = element;
}
mountComponent(container) {
const Component = this._element.type;
const componentInstance = new Component(this._element.props);
this._instance = componentInstance;
if (componentInstance.componentWillMount) {
componentInstance.componentWillMount();
}
const markup = this.performInitialMount(container);
if (componentInstance.componentDidMount) {
componentInstance.componentDidMount();
}
return markup;
}
performInitialMount(container) {
const renderedElement = this._instance.render();
const child = instantiateFeactComponent(renderedElement);
this._renderedComponent = child;
return FeactReconciler.mountComponent(child, container);
}
}
const TopLevelWrapper = function(props) {
this.props = props;
};
TopLevelWrapper.prototype.render = function() {
return this.props;
};
function instantiateFeactComponent(element) {
if (typeof element.type === 'string') {
return new FeactDOMComponent(element);
} else if (typeof element.type === 'function') {
return new FeactCompositeComponentWrapper(element);
}
}
const FeactReconciler = {
mountComponent(internalInstance, container) {
return internalInstance.mountComponent(container);
}
};
const Feact = {
createElement(type, props, children) {
const element = {
type,
...