ZhangCheng-zh / blog

记录一些code
0 stars 0 forks source link

React analysis #9

Open ZhangCheng-zh opened 2 years ago

ZhangCheng-zh commented 2 years ago

step

key details

diff

hooks

connect react basic logic to view

view
life cycle function(wrap hooks)
   hooks
react basic runtime

Build my own react

createElement and render function

const Didact = {
    createElement,
    render
}

function createElement(type, props, ...children) {
    return {
        type,
        props: {
            ...props,
            children: children.map(child =>
                typeof child === 'object'
                ? child
                : createTextElement(child))
        }
    }
}

function createTextElement(text) {
    return {
        type: 'TEXT_ELEMENT',
        props: {
            nodeValue: text,
            children: []
        }
    }
}

function render(element, container) {
    const dom = element.type === 'TEXT_ELEMENT' ? element.createTextElement('') : document.createElement(element)
    element.props.children.forEach(child => render(child, dom))

    // add props to element
    const isProperty = key => key !== 'children'
    Object.keys(element.props)
    .filter(isProperty)
    forEach(name => dom[name] = element.props[name])

    container.appendChild(dom)
}

/** @jsx Didact.createElement */
const element = (
    <div id='foo'>
        <a>bar</a>
        <b />
    </div>
)

const container = document.getElementById('root')
ReactDOM.render(element, container)

Step 3: curcurrent mode