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>
  )
}
相关推荐
小叶lr5 小时前
jenkins打包前端样式丢失/与本地不一致问题
运维·前端·jenkins
浩星5 小时前
electron系列1:Electron不是玩具,为什么桌面应用需要它?
前端·javascript·electron
ZC跨境爬虫5 小时前
Scrapy工作空间搭建与目录结构解析:从初始化到基础配置全流程
前端·爬虫·python·scrapy·自动化
小村儿5 小时前
连载04-最重要的Skill---一起吃透 Claude Code,告别 AI coding 迷茫
前端·后端·ai编程
_院长大人_6 小时前
Vue + ECharts 实现价格趋势分析图
前端·vue.js·echarts
疯笔码良6 小时前
【Vue】自适应布局
javascript·vue.js·css3
浩星6 小时前
electron系列2:搭建专业Electron开发环境
javascript·typescript·electron
IT_陈寒6 小时前
Vite的alias配置把我整不会了,原来是这个坑
前端·人工智能·后端
万物得其道者成6 小时前
Cursor 提效实战:我的前端 Prompt、审查 SKILL、MCP 接入完整方法
前端·prompt
酒鼎7 小时前
学习笔记(12-02)事件循环 - 实战案例 —⭐
前端·javascript