【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 分钟前
Promise async/await与fetch的概念
前端·javascript·html
Mintopia9 分钟前
Web 安全与反编译源码下的权限设计:构筑前后端一致的防护体系
前端·安全
输出输入11 分钟前
前端核心技术
开发语言·前端
Mintopia15 分钟前
Web 安全与反编译源码下的权限设计:构建前后端一体的信任防线
前端·安全·编译原理
林深现海36 分钟前
Jetson Orin nano/nx刷机后无法打开chrome/firefox浏览器
前端·chrome·firefox
黄诂多1 小时前
APP原生与H5互调Bridge技术原理及基础使用
前端
前端市界1 小时前
用 React 手搓一个 3D 翻页书籍组件,呼吸海浪式翻页,交互体验带感!
前端·架构·github
早點睡3901 小时前
高级进阶 ReactNative for Harmony 项目鸿蒙化三方库集成实战:react-native-drag-sort
react native·react.js·harmonyos
文艺理科生1 小时前
Nginx 路径映射深度解析:从本地开发到生产交付的底层哲学
前端·后端·架构
千寻girling1 小时前
主管:”人家 Node 框架都用 Nest.js 了 , 你怎么还在用 Express ?“
前端·后端·面试