【React】forwardRef 用法

文章目录

基本用法

  • forwardRef:允许你的组件使用 ref 将一个 DOM 节点暴露给父组件。
import {
    
     forwardRef } from 'react';

const MyInput = forwardRef((props, ref) => {
    
    
  // ...
});
  • 案例分析:ref 属性是 React 的特殊属性,不能直接使用。
import {
    
    useRef} from 'react'

function InputCom({
     
     ref}) {
    
    
  return (
    <input type='text' ref={
    
    ref} />
  )
}

function App() {
    
    
  const inpRef = useRef(null)

  const focus = () => {
    
    
    inpRef.current?.focus()
  }

  return (
    <>
      <InputCom ref={
    
    inpRef} />
    </>
  )
}
  • 上面就会弹出报错信息:
Warning: InputCom: `ref` is not a prop. Trying to access it will result in `undefined` being returned. 
If you need to access the same value Within the child component, you should pass it as a company's prop.
// 警告:InputCom: 'ref不是一个prop。试图访问它将导致返回undefine。如果你需要在子组件中访问相同的值,你应该把它作为公司的prop传递。
  • 如果想传递 ref,这时候就要借助 forwardRef 函数
import {
    
     forwardRef, useRef } from "react";

const InputCom = forwardRef((props, ref) => {
    
    
  return <input type="text" ref={
    
    ref} />;
});

export default function ProRef() {
    
    
  const inpRef = useRef(null);

  const focus = () => {
    
    
    inpRef.current?.focus();
  };

  return (
    <>
      <InputCom ref={
    
    inpRef} />
      <button onClick={
    
    focus}>focus</button>
    </>
  );
}

猜你喜欢

转载自blog.csdn.net/qq_45677671/article/details/131370760