简单手写实现元素的Ref
继续学习写源码系列,本系列是学习系列。
- 简单手写实现 React 的 createElement 和 render,里面有准备工作,不再赘述。
- 简单手写实现 react 的函数组件
- 简单手写实现 react 的类组件
- 简单手写实现 React 类组件的 state 更新
- 简单手写实现 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
<input ref={this.a}>
其实本质就是将this.a.current
赋值为input
的真实 DOMReact.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
打开自己文件的路径
正常运行,✌️~~~