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>
  )
}
相关推荐
颜酱8 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
失忆爆表症9 小时前
05_UI 组件库集成指南:Shadcn/ui + Tailwind CSS v4
前端·css·ui
小迷糊的学习记录9 小时前
Vuex 与 pinia
前端·javascript·vue.js
发现一只大呆瓜9 小时前
前端性能优化:图片懒加载的三种手写方案
前端·javascript·面试
不爱吃糖的程序媛9 小时前
Flutter 与 OpenHarmony 通信:Flutter Channel 使用指南
前端·javascript·flutter
利刃大大9 小时前
【Vue】Element-Plus快速入门 && Form && Card && Table && Tree && Dialog && Menu
前端·javascript·vue.js·element-plus
NEXT0610 小时前
AI 应用工程化实战:使用 LangChain.js 编排 DeepSeek 复杂工作流
前端·javascript·langchain
念风零壹10 小时前
AI 时代的前端技术:从系统编程到 JavaScript/TypeScript
前端·ai
光影少年10 小时前
react的hooks防抖和节流是怎样做的
前端·javascript·react.js
小毛驴85011 小时前
Vue 路由示例
前端·javascript·vue.js