ref 屬性是 React 的特殊屬性,不能直接傳遞使用。
借助 forwardRef 轉(zhuǎn)發(fā) 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>
</>
);
}