当前位置: 首页 > article >正文

React学习笔记20

一、React.forward

1.1、作用

通过ref暴露子组件的DOM

1.2、场景说明

 1.3、语法实现

// 子组件
const Input = forwardRef((props,ref)=>{
    return <input type="text" ref={ref} />
})

// 父组件
function father_component(){
    const inputRef=useRef(null)
    const focus=(ref)=>{
        ref.current.focus()
    }
    return(
        <>
            <Input ref={inputRef}></Input>
            <button onClick={()=>{focus(inputRef)}}></button>
        </>
    )
}

二、useInperativeHandle

1.1、作用

通过ref暴露子组件中的方法

1.2、场景说明

1.3、语法实现

// 子组件
const Input = forwardRef((props,ref)=>{
    // 实现聚焦逻辑
    const inputRef=useRef(null)
    const focus_input=()=>{
        inputRef.current.focus()
    }
    // 暴露聚焦方法
    useImperativeHandle(ref,()=>{
        return {
            focus_input
        }
    })
    return <input type="text" ref={inputRef} />
})

// 父组件
function father_component(){
    const sonRef=useRef(null)
    const focusHandle=(ref)=>{
        
    }
    return(
        <>
            <Input ref={sonRef}></Input>
            <button onClick={()=>sonRef.current.focus_input()}></button>
        </>
    )
}

 下一章:React学习笔记21:类组件


http://www.kler.cn/a/594738.html

相关文章:

  • 面试总结之基于 Room + WorkManager 的离线缓存系统实践
  • 【在 Element UI 的表格中为表头添加必填星号标识(红色*)】
  • Git远程拉取和推送配置
  • B站pwn教程笔记-5
  • 拓展 Coco AI 功能 - 智能检索 Hexo 博客
  • 基于MATLAB的涡旋光和高斯光叠加产生平顶光
  • 关于前端路由
  • 乐维网管平台核心功能解析(三)——告警关联资产
  • Vue的根路径为什么不能作为跳板跳转到其他页面
  • Acrobat DC v25.001 最新专业版已破,像word一样编辑PDF!
  • 第二天 流程控制(if/for/while) - 列表/元组/字典操作
  • centos 磁盘重新分割,将原来/home 下部分空间转移到 / 根目录下
  • 自定义myshell(精讲)
  • 如何让节卡机器人精准对点?
  • 谷歌最新发布Gemma3大模型:小规模高性能
  • 一种很新的“工厂”打开方式---智慧工厂
  • Anthropic 正在开发 Harmony:Claude 即将支持本地文件操作
  • K8S学习之基础三十七:prometheus监控node资源
  • PH热榜 | 2025-03-20
  • 轻松迁移 Elasticsearch 数据:如何将自建索引导出并导入到另一个实例