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>
  )
}
相关推荐
几何心凉13 分钟前
如何使用 React Hooks 替代类组件的生命周期方法?
前端·javascript·react.js
小堃学编程20 分钟前
前端学习(1)—— 使用HTML编写一个简单的个人简历展示页面
前端·javascript·html
hnlucky1 小时前
通俗易懂版知识点:Keepalived + LVS + Web + NFS 高可用集群到底是干什么的?
linux·前端·学习·github·web·可用性测试·lvs
懒羊羊我小弟2 小时前
使用 ECharts GL 实现交互式 3D 饼图:技术解析与实践
前端·vue.js·3d·前端框架·echarts
前端小巷子2 小时前
CSS3 遮罩
前端·css·面试·css3
运维@小兵2 小时前
vue访问后端接口,实现用户注册
前端·javascript·vue.js
雨汨2 小时前
web:InfiniteScroll 无限滚动
前端·javascript·vue.js
小盐巴小严2 小时前
正则表达式
javascript·正则表达式
Samuel-Gyx2 小时前
前端 CSS 样式书写与选择器 基础知识
前端·css
天天打码3 小时前
Rspack:字节跳动自研 Web 构建工具-基于 Rust打造高性能前端工具链
开发语言·前端·javascript·rust·开源