react的ref原理

1、什么是ref

ref使用时,可以拿到对应的元素真实dom ,或者类组件的实例 ,或者传入React.forwardRef包装后的 函数组件

2、dom元素使用ref

import React from './react';
import ReactDOM from './react-dom';
class Sum extends React.Component{
   
  numberA
  numberB
  result
  constructor(props){
   
    super(props);
    this.numberA = React.createRef();//{current:null}
    this.numberB = React.createRef();
    this.result = React.createRef();
  }
  handleClick = (event)=>{
   
    let numberA = this.numberA.current.value;
    let numberB = this.numberB.current.value;
    this.result.current.value = parseFloat(numberA)+parseFloat(numberB);
  }
  render(){
   
    return (
      <>
        <input ref={
   this.numberA}/>
        <input ref={
   this.numberB}/>
        <button onClick={
   this.handleClick}>+</button>
        <input ref={
   this.result}/>
      </>
    )
  }
}
ReactDOM.render(<Sum/>,document.getElementById('root'));

react.js实现这个函数
返回一个对象

function createRef(){
   
    return {
   current:null};
}

createRef就是行会一个对象 {current:null}

ref, key是通过props属性传入给createElement ,但是里面删除这个属性 提取出来直接放在最外层导出,就是虚拟dom最外层属性, 32行

function createElement(type,config,children){
   
    let ref;//是用来获取虚拟DOM实例的
    let key;//用来区分同一个父亲的不同儿子的
    if(config){
   
        delete config.__source;
        delete config.__self;
        ref = config.ref;
        delete config.ref;
        key = config.key;
        delete config.key;
    }
    let props = {
   ...config};//没有ref和key
    if(arguments.length>3){
   //如果参数大于3个,说明有多个儿子
        //核心就是把字符串或者说数字类型的节点转换成对象的形式
        props.children = Array.prototype.slice.call(arguments,2).map
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值