likes
comments
collection
share

简单手写实现元素的Ref

作者站长头像
站长
· 阅读数 52

继续学习写源码系列,本系列是学习系列。

  1. 简单手写实现 React 的 createElement 和 render,里面有准备工作,不再赘述。
  2. 简单手写实现 react 的函数组件
  3. 简单手写实现 react 的类组件
  4. 简单手写实现 React 类组件的 state 更新
  5. 简单手写实现 React 类组件的 state 批量更新

本文的目标是,手写实现元素的Ref

TL;DR

  • createRef 简单的返回{current:null}
  • 元素身上的ref,指向的就是{current:null},解析属性的时候,其current赋值为元素 DOM即可

准备工作

先将index.js的点击事件略微修改

// import React from './source/react';
// import ReactDOM from './source/react-dom';
import React from 'react';
import ReactDOM from 'react-dom';
class Sum extends React.Component {
  constructor(props) {
    super(props);
    this.a = React.createRef();
    this.b = React.createRef();
    this.result = React.createRef();
  }
  handleAdd = () => {
    let a = this.a.current.value;
    let b = this.b.current.value;
    this.result.current.value = a + b;
  };
  render() {
    return (
      <>
        <input ref={this.a} />+<input ref={this.b} />
        <button onClick={this.handleAdd}>=</button>
        <input ref={this.result} />
      </>
    );
  }
}
const reactElement = <Sum />;

ReactDOM.render(reactElement, document.getElementById('root'));

输入框输入 1,2,点击=之后,看到 12:

简单手写实现元素的Ref

分析 ref

  1. <input ref={this.a}>其实本质就是将this.a.current赋值为input的真实 DOM
  2. React.createRef()的返回值始终一致就是{current:null}

实现

1.增加 createRef 方法

丝毫无压力,直接在react.js里,加个方法,返回``即可

// react.js
const createRef = () => ({ current: null });
const React = {
  createElement,
  Component,
  createRef,
};

2.解析 ref 属性的时候,赋值当前元素 DOM

这个也简单,props 属性解析的时候,赋值就好

function updateProps(DOM, props) {
  // ...
  if (key === 'children') continue;
  if (key === 'ref') {
    // props是 {ref:{current:null},children:null}
    console.log('ref属性赋值', props, key, props[key]);
    props[key].current = DOM;
    continue;
  }
}

老规矩,index.js打开自己文件的路径

正常运行,✌️~~~

转载自:https://juejin.cn/post/7145646451228901406
评论
请登录