本文正在参加「金石计划」
useImperativeHandle(ref, createHandle, dependencies?)
自定义子组件转发ref暴露给父组件的 current 的值而不是暴露出整个 node
-
ref
forwardRef
渲染函数第二个参数 -
createHandle
没有参数返回替代current的数据
import { forwardRef, useRef, useImperativeHandle } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => {
return {
focus() {
inputRef.current.focus();
},
scrollIntoView() {
inputRef.current.scrollIntoView();
},
};
}, []);
return <input {...props} ref={inputRef} />;
});
注意
-
不要过度使用
你没法通过 prop 来表达 命令式 行为的时候才使用 ref
-
如果可以通过 prop 实现,那就不应该使用 ref
Effect 可以实现一些功能