react Hooks 父组件调用子组件函数、获取子组件属性

子组件

复制代码
import { forwardRef, useImperativeHandle } from 'react'

// 定义子组件的 ref 类型
export interface ChildRef {
  childMethod: () => void
  childValue: string
}

const Child = forwardRef<ChildRef>((props, ref) => {
  // 暴露给父组件的方法和属性
  useImperativeHandle(ref, () => ({
    childMethod: () => {
      console.log('子组件方法被调用')
    },
    childValue: 'child value'
  }))

  return <div>子组件</div>
})

export default Child

父组件

复制代码
import { useRef } from 'react'
import Child, { type ChildRef } from './Child'

const Parent = () => {
  const childRef = useRef<ChildRef>(null)

  const handleClick = () => {
    // 调用子组件方法
    childRef.current?.childMethod()
    // 访问子组件属性
    console.log(childRef.current?.childValue)
  }

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={handleClick}>调用子组件方法</button>
    </div>
  )
}

获取使用使用 Context(适用于多层级组件通信

复制代码
context.ts

import { createContext } from 'react'

interface ContextType {
  parentMethod: () => void
  parentValue: string
}

export const MyContext = createContext<ContextType>({
  parentMethod: () => {},
  parentValue: ''
})

Parent.tsx

const Parent = () => {
  const contextValue = {
    parentMethod: () => {
      console.log('父组件方法被调用')
    },
    parentValue: 'parent value'
  }

  return (
    <MyContext.Provider value={contextValue}>
      <Child />
    </MyContext.Provider>
  )
}

Child.tsx

import { useContext } from 'react'
import { MyContext } from './context'

const Child = () => {
  const { parentMethod, parentValue } = useContext(MyContext)

  return (
    <div>
      <button onClick={parentMethod}>调用父组件方法</button>
      <div>父组件值: {parentValue}</div>
    </div>
  )
}
相关推荐
NMBG22几秒前
外卖综合项目
java·前端·spring boot
小白阿龙1 分钟前
样式不生效/被覆盖(CSS优先级陷阱)
前端·css
flashlight_hi3 分钟前
LeetCode 分类刷题:110. 平衡二叉树
javascript·算法·leetcode
Beginner x_u4 分钟前
Vue 事件机制全面解析:原生事件、自定义事件与 DOM 冒泡完全讲透
前端·javascript·vue.js·dom
Emma_Maria5 分钟前
关于vant-ui-vue 的datepicker 时间选择错乱问题的处理
前端·vue.js·ui
Dabei10 分钟前
Android 语音助手简单实现与语音助手“执行任务”交流
android·前端
dongczlu12 分钟前
iOS 循环引用篇 菜鸟都能看懂
前端
Alsn8614 分钟前
26.IDEA 专业版中创建简单的 Web 项目并打包部署到本地Tomcat 9
前端·tomcat·intellij-idea
霍理迪15 分钟前
HTML行内块标签——img、表单、音视频标签
前端·html
小小前端_我自坚强16 分钟前
边缘函数 (Edge Functions)详解
前端