【REACT18.x】CRA+TS+ANTD5.X实现useImperativeHandle让父组件修改子组件的数据

本实例主要是记录useRef在自定义组件上面的使用方法,包括子组件暴漏方法或属性给父组件,forwardRef useImperativeHandle等的实战

实现效果

代码实现

  • 父组件
js 复制代码
import React, { useRef } from 'react'
import UseRefCustomChildDemo, { UseRefCustomChildDemoRef } from './UseRefCustomChildDemo'
import { Button, Flex, Space } from 'antd'
function UseRefCustomDemo() {
    const useChildRef = useRef<UseRefCustomChildDemoRef>(null)
    return (
        <div>
            <h2>UseRefCustomDemo</h2>
            <hr />
            <Space direction='vertical'>
                <UseRefCustomChildDemo ref={useChildRef} username='zs' />
                <Flex justify='center' gap={'20px'}>
                    <Button
                        onClick={() => {
                            console.log(useChildRef)
                            useChildRef.current?.handleFocus()
                        }}
                    >
                        获取焦点
                    </Button>
                    <Button
                        type='primary'
                        onClick={() => {
                            useChildRef.current?.handleSelect()
                        }}
                    >
                        选中文字
                    </Button>
                    <Button
                        type='primary'
                        danger
                        onClick={() => {
                            useChildRef.current?.handleClick()
                        }}
                    >
                        修改信息
                    </Button>
                </Flex>
            </Space>
        </div>
    )
}
export default UseRefCustomDemo
  • 子组件
js 复制代码
import { Flex } from 'antd'
import React, { forwardRef, ReactNode, useImperativeHandle, useRef } from 'react'
import { useImmer } from 'use-immer'

type Props = { children?: ReactNode; username: string }

export interface UseRefCustomChildDemoRef {
    handleFocus: () => void
    handleSelect: () => void
    handleClick: () => void
}

const UseRefCustomChildDemo = forwardRef<UseRefCustomChildDemoRef, Props>((props, ref) => {
    const { username } = props
    const [userInfo, setUserInfo] = useImmer({
        name: 'lisi',
        age: 18
    })
    function handleClick(): void {
        setUserInfo(draft => {
            draft.age += 1
        })
    }

    const inputRef = useRef<HTMLInputElement>(null)

    useImperativeHandle(ref, () => {
        return {
            handleFocus() {
                inputRef.current!.focus()
            },
            handleSelect() {
                inputRef.current?.select()
            },
            handleClick() {
                handleClick()
            }
        }
    }, [])

    return (
        <div>
            <p>姓名:{username ? username : userInfo.name}</p>
            <p>年龄:{userInfo.age}</p>
            <Flex justify='center' gap={'20px'}>
                <input type='text' ref={inputRef} />
                <button onClick={handleClick}>修改年龄</button>
            </Flex>
        </div>
    )
})
UseRefCustomChildDemo.displayName = 'UseRefCustomChildDemo'

export default UseRefCustomChildDemo
相关推荐
一路上__有你3 分钟前
闲来无事,写一篇文章吧!
前端·javascript·vue.js
keep_di3 分钟前
05-vue3+ts中axios的封装
前端·vue.js·ajax·typescript·前端框架·axios
JiKun19 分钟前
ECMA 2024(ES15) 新特性
前端·javascript
百锦再26 分钟前
从 .NET 到 Java 的转型指南:详细学习路线与实践建议
android·java·前端·数据库·学习·.net·数据库架构
i小杨39 分钟前
前端埋点(打点)方案
前端·状态模式
前端加油站1 小时前
时间转换那些事
前端·javascript
风清云淡_A1 小时前
【VUECLI】node.js打造自己的前端cli脚手架工具
前端·node.js
YuspTLstar1 小时前
一文掌握Redux-toolkit核心原理
前端·react.js
云枫晖1 小时前
手写Promise-静态方法all和allSettled
前端·javascript
weixin_456904271 小时前
前端开发时npm install报错解决方案
前端·npm·node.js