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>
  )
}
相关推荐
像风一样自由20208 分钟前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
伍哥的传说18 分钟前
React 各颜色转换方法、颜色值换算工具HEX、RGB/RGBA、HSL/HSLA、HSV、CMYK
深度学习·神经网络·react.js
aiprtem1 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊1 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术1 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
GISer_Jing1 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止1 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall1 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴2 小时前
简单入门Python装饰器
前端·python
袁煦丞2 小时前
数据库设计神器DrawDB:cpolar内网穿透实验室第595个成功挑战
前端·程序员·远程工作