请说说什么是useImperativeHandle?

请说说什么是useImperativeHandle?,第1张

请说说什么是useImperativeHandle?

封装组件对外通过 ref 暴露的信息。
常用场景是子组件不希望父组件直接 *** 作 dom,而是通过暴露固定方法

下面方法中,父组件通过 inputRef 只能获取到 value 属性,而没有其他的DOM信息

import React, { useRef, useImperativeHandle, useEffect } from 'react';const Parent = () => {  const inputRef = useRef(null);  useEffect(() => {    setTimeout(() => {      if (inputRef.current) {        console.log(inputRef.current);        inputRef.current.value;      }    }, 3000);  }, []);  return <Child ref={inputRef} />}const ChildComponent = ({ propsRef }) => {  useImperativeHandle(propsRef, () => ({    value: propsRef.current.value  }), [propsRef]);  // 这里使用了 uncontrolled component  return <input ref={propsRef} defaultValue='xxx' />}const Child = React.forwardRef((props, ref) => {  return <ChildComponent {...props} propsRef={ref} />});export default Parent;

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4919505.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存