React - useImperativeHandle与forwardRef

// FancyInput组件作为子组件 函数组件
const FancyInput = React.forwardRef(()=> (props, ref) {
  const inputRef = useRef();
  // 命令式的给`ref.current`赋值个对象
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus()
    }
  }));
  return <input ref={inputRef} ... />
})

// Example组件作为父组件
function Example() {
  const fancyInputRef = useRef()
  const focus = () => {
    fancyInputRef.current.focus()
  }
  return (
    <><FancyInput ref={fancyInputRef} /></>
  )
}

 当子组件为类组件时

export default React.forwardRef((props, ref) => <Component
  {...props}
  innerRef={ref}
/>);
// 这个时候innerRef就变成了ref

 

posted @   马铃薯头抽雪茄  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示