【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
相关推荐
LYFlied2 分钟前
从 Vue 到 React,再到 React Native:资深前端开发者的平滑过渡指南
vue.js·react native·react.js
爱喝白开水a18 分钟前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌4118 分钟前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
吃杠碰小鸡1 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone1 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_09012 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农2 小时前
Vue 2.3
前端·javascript·vue.js
夜郎king2 小时前
HTML5 SVG 实现日出日落动画与实时天气可视化
前端·html5·svg 日出日落
夏幻灵3 小时前
HTML5里最常用的十大标签
前端·html·html5
Mr Xu_4 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js