React hooks useImperativeHandle用法示例

useImperativeHandle可以给React.forward处理后的函数组件接收到的ref对象拓展功能

方式一(不使用forwardRef)

import React, { forwardRef, useImperativeHandle, useState } from 'react'

// 定义子组件 CustomInput,并接受 ref 传递
const CustomInput = (props: any) => {
    const { onRef } = props
    const [value, setValue] = useState('')
    // 创建一个内部 ref 并绑定到 input 元素上
    const inputRef = React.useRef(null)

    // 使用 useImperativeHandle 来暴露 focus 方法
    useImperativeHandle(onRef, () => ({
        // 父组件可以通过 ref 调用此方法聚焦输入框
        clearInput: clearInput,
    }))

    const clearInput = () => {
        setValue('')
        // 如果 inputRef 已经关联到 DOM 元素,则同时触发其值清空
        if (inputRef.current) {
            inputRef.current.value = ''
        }
    }

    return (
        <>
            <input
                ref={inputRef}
                type="text"
                value={value}
                onChange={(e) => setValue(e.target.value)}
            />
        </>
    )
}

// 在父组件中使用 CustomInput 并获取 ref
function MyApp() {
    const inputRef = React.useRef(null)

    // 当需要时,可以直接调用 ref 上的方法
    const handleFocus = () => {
        if (inputRef.current) {
            inputRef.current.clearInput()
        }
    }

    return (
        <>
            <CustomInput onRef={inputRef} />
            <button onClick={handleFocus}>Focus the Input</button>
        </>
    )
}

export default MyApp

方式二(使用forwardRef)

import React, { forwardRef, useImperativeHandle, useState } from 'react'

// 定义子组件 CustomInput,并接受 ref 传递
const CustomInput = forwardRef((props, ref) => {
    const [value, setValue] = useState('')
    // 创建一个内部 ref 并绑定到 input 元素上
    const inputRef = React.useRef(null)

    // 使用 useImperativeHandle 来暴露 focus 方法
    useImperativeHandle(ref, () => ({
        // 父组件可以通过 ref 调用此方法聚焦输入框
        clearInput: clearInput,
    }))

    const clearInput = () => {
        setValue('')
        // 如果 inputRef 已经关联到 DOM 元素,则同时触发其值清空
        if (inputRef.current) {
            inputRef.current.value = ''
        }
    }

    return (
        <>
            <input
                ref={inputRef}
                type="text"
                value={value}
                onChange={(e) => setValue(e.target.value)}
            />
        </>
    )
})

// 在父组件中使用 CustomInput 并获取 ref
function MyApp() {
    const inputRef = React.useRef(null)

    // 当需要时,可以直接调用 ref 上的方法
    const handleFocus = () => {
        if (inputRef.current) {
            inputRef.current.clearInput()
        }
    }

    return (
        <>
            <CustomInput ref={inputRef} />
            <button onClick={handleFocus}>Focus the Input</button>
        </>
    )
}

export default MyApp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值