传递 React 的特殊属性 ref

ref 属性是 React 的特殊属性,不能直接传递使用。

借助 forwardRef 转发 ref 属性

举例如下:

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} />
      <br />
      <button onClick={focus}>focus</button>
    </>
  );
}
posted @ 2023-10-07 16:43  孤持的庄稼人  阅读(48)  评论(0)    收藏  举报