useImperativeHandle
useImperativeHandle 是 React 中的一个 Hook,它能让你自定义由 ref 暴露出来的句柄。
import { forwardRef, useRef, useImperativeHandle } from "react";
const Post = forwardRef((props, ref) => {
useImperativeHandle(
ref,
() => {
return {
scrollAndFocusAddComment() {
// 向外暴露了一个 scrollAndFocusAddComment 方法。
// ...
},
};
},
[]
);
return (
<>
<article>
<p>Welcome to my blog!</p>
</article>
</>
);
});
export default Post;