react之useRef和createRef

react之useRef和createRef,第1张

一、useRef和createRef 1. 作用于普通DOM

import { Input, Button } from 'antd';
import { useRef, createRef } from 'react';

import type { InputRef } from 'antd';

const RefDemo = () => {
  const inputEL = useRef(null);
  const inputEL2 = useRef(null);
  const inputEL3 = createRef();

  const getInput = () => {
    console.log('antd DOM', inputEL.current?.input?.value);
    console.log('原生 DOM', inputEL2.current?.value);
    console.log('createRef', inputEL3.current?.value);
  };

  return (
    
      

antd Input:{width: 167}} />

原生 Input:

createRef Input:

); }; export default RefDemo;
2. 作用于子组件,需要用到两个方法 useImperativeHandle 和 forwardRef forwardRef:包裹要添加ref的子组件,有两个参数,组件的props和组件的refuseImperativeHandle:两个参数,组件的 ref 和一个回调函数,返回值是子组件的方法或者变量,提供给父组件调用注意!在父组件中使用 ref 去更新子组件,只是子组件更新,父组件不会同步更新,需要手动更新
import { Button } from 'antd';
import { useRef, useImperativeHandle, forwardRef, useState } from 'react';

const Child = forwardRef((props, ref) => {

  const [count, setCount] = useState(0);

  useImperativeHandle(ref, () => ({
    count: count,
    changeCount() {
      setCount(count + 1);
    }
  }));

  return (
    
      

子组件count: { count }

); }); type ChildRefType = { count: number, changeCount: () => void; } const RefDemo = () => { const childRef = useRef(); const [reload, setReload] = useState(false); const changeChild = () => { childRef.current?.changeCount(); }; return (

父组件:count:{childRef.current?.count}

); }; export default RefDemo;
注意!此方法不适用于createRef,原因如下,每次父组件渲染都会重新创建ref,所获取的值都为undefined 二、useRef和createRef区别 createRef会在组件每次渲染的时候重新创建useRef只会在组件首次渲染时创建
import { useState, useRef, createRef } from 'react';
import { Button } from 'antd';

const RefDemo = () => {
  
  const [count, setCount] = useState(0);
  
  const inputEL = useRef(null);
  const inputEL2 = createRef();

  const showCount = () => {
    console.log('useRef Input:', inputEL.current?.value);
    console.log('createRef Input:', inputEL2.current?.value);
  };

  const updateComponent = () => {
    setCount(count + 1);
  };

  console.log(inputEL.current?.value, inputEL2.current?.value, `组件${count === 0 ? '初' : count}次渲染`);

  return(
    
      

useRef Input:

createRef Input:

); }; export default RefDemo;

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/925466.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存