【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
相关推荐
rayufo几秒前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk4 分钟前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
摘星编程44 分钟前
React Native + OpenHarmony:Timeline垂直时间轴
javascript·react native·react.js
2501_944525542 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
jin1233222 小时前
React Native鸿蒙跨平台完成剧本杀组队详情页面,可以复用桌游、团建、赛事等各类组队详情页开发
javascript·react native·react.js·ecmascript·harmonyos
李白你好2 小时前
Burp Suite插件用于自动检测Web应用程序中的未授权访问漏洞
前端
刘一说3 小时前
Vue 组件不必要的重新渲染问题解析:为什么子组件总在“无故”刷新?
前端·javascript·vue.js
jin1233223 小时前
基于React Native鸿蒙跨平台移动端表单类 CRUD 应用,涵盖地址列表展示、新增/编辑/删除/设为默认等核心操作
react native·react.js·ecmascript·harmonyos
徐同保4 小时前
React useRef 完全指南:在异步回调中访问最新的 props/state引言
前端·javascript·react.js
浮游本尊4 小时前
React 18.x 学习计划 - 第十三天:部署与DevOps实践
学习·react.js·状态模式