【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
相关推荐
昔人'36 分钟前
`list-style-type: decimal-leading-zero;`在有序列表`<ol></ol>` 中将零添加到一位数前面
前端·javascript·html
岁月宁静6 小时前
深度定制:在 Vue 3.5 应用中集成流式 AI 写作助手的实践
前端·vue.js·人工智能
心易行者7 小时前
10天!前端用coze,后端用Trae IDE+Claude Code从0开始构建到平台上线
前端
saadiya~7 小时前
ECharts 实时数据平滑更新实践(含 WebSocket 模拟)
前端·javascript·echarts
fruge7 小时前
前端三驾马车(HTML/CSS/JS)核心概念深度解析
前端·css·html
百锦再7 小时前
Vue Scoped样式混淆问题详解与解决方案
java·前端·javascript·数据库·vue.js·学习·.net
烛阴7 小时前
Lua 模块的完整入门指南
前端·lua
浪里行舟8 小时前
国产OCR双雄对决?PaddleOCR-VL与DeepSeek-OCR全面解析
前端·后端
znhy@1239 小时前
CSS易忘属性
前端·css
瓜瓜怪兽亚9 小时前
前端基础知识---Ajax
前端·javascript·ajax