8. 实现事件绑定

48 阅读1分钟

本节课我们来实现给我们的mini-react项目添加绑定事件。

  • 先在app.jsx中添加click事件
import React from './core/React.js';
​
function Counter({ num }) {
  function handleClick() {
    console.log("click")
  }
  return <div>
    count: {num} 
    <button onClick={handleClick}>点击</button>
  </div>
}
​
function App() {
  return <div>
    hi-mini-react
    <Counter num={10}></Counter> 
    {/* <Counter num={20}></Counter> */}
  </div>
}
export default App;
  • 通过打印,观察一下fiber中的button,方便后续处理
function initChildren(fiber, children) {
    console.log('fiber -->', fiber)
    let prevChild = null
    children.forEach((child, index) => {
        const newFiber = {
            type: child.type,
            props: child.props,
            child: null,
            parent: fiber,
            sibling: null,
            dom: null
        }
        if (index === 0) {
            fiber.child = newFiber
        } else {
            prevChild.sibling = newFiber
        }
        prevChild = newFiber
    }) 
}

1.png

  • 于是我们就想只要是on开头的,我们就认为是一个事件,只要是事件开头的,把事件名和值 给dom绑定上,我们在updateProps的时候处理
function updateProps(dom, props) {
    Object.keys(props).forEach((key) => {
        if (key !== "children") {
            // onClick -> click
            if (key.startsWith("on")) {
                const eventType = key.slice(2).toLowerCase()
                dom.addEventListener(eventType, props[key])
            } else {
                dom[key] = props[key];
            }
        }
    });
}
  • 这个时候就有点击事件了,以上演示的是click,其它的事件也是一样的道理

2.png