You need to enable JavaScript to run this app. React中如何调用定义在useEffect内部的指定函数?
优惠活动
大模型
产品
解决方案
定价
更多

React中如何调用定义在useEffect内部的指定函数?

解决方案

你可以通过React的forwardRef+useImperativeHandle组合,将子组件内部的方法暴露给父组件调用,这是官方推荐的子组件对外暴露命令式方法的实现方式。

步骤1:修改CornerExpand子组件

  • 用forwardRef包裹组件,接收父组件传递的ref
  • 新增一个ref存储fullscreen函数的引用,在useEffect内部给这个ref赋值
  • 用useImperativeHandle把fullscreen方法暴露给父组件的ref

修改后的完整代码:

import { useEffect, useRef, forwardRef, useImperativeHandle } from "react"
import * as blobs2Animate from "blobs/v2/animate"

// 定义暴露给父组件的方法类型
export interface CornerExpandHandle {
  fullscreen: () => void
}

export const CornerExpand = forwardRef<CornerExpandHandle>((_, ref) => {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  // 存储fullscreen函数的引用
  const fullscreenRef = useRef<() => void>()

  useEffect(() => {
    const canvas = canvasRef.current!
    const ctx = canvas.getContext("2d")
    const animation = blobs2Animate.canvasPath()

    const width = canvas.clientWidth * window.devicePixelRatio
    const height = canvas.clientHeight * window.devicePixelRatio
    canvas.width = width
    canvas.height = height

    const renderAnimation = () => {
      if (!ctx) return
      ctx.clearRect(0, 0, width, height)
      ctx.fillStyle = "#E0F2FE"
      ctx.fill(animation.renderFrame())
      requestAnimationFrame(renderAnimation)
    }
    requestAnimationFrame(renderAnimation)

    const size = Math.min(width, height) * 1
    const defaultOptions = () => ({
      blobOptions: {
        seed: Math.random(),
        extraPoints: 36,
        randomness: 0.7,
        size,
      },
      canvasOptions: {
        offsetX: -size / 2.2,
        offsetY: -size / 2.2,
      },
    })

    const loopAnimation = () => {
      animation.transition({
        duration: 4000,
        timingFunction: "ease",
        callback: loopAnimation,
        ...defaultOptions(),
      })
    }

    animation.transition({
      duration: 0,
      callback: loopAnimation,
      ...defaultOptions(),
    })

    const fullscreen = () => {
      const options = defaultOptions()
      options.blobOptions.size = Math.max(width, height) * 1.6
      options.blobOptions.randomness = 1.4
      options.canvasOptions.offsetX = -size / 2
      options.canvasOptions.offsetY = -size / 2
      animation.transition({
        duration: 2000,
        timingFunction: "elasticEnd0",
        ...options,
      })
    }
    // 给fullscreenRef赋值
    fullscreenRef.current = fullscreen
  }, [])

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    fullscreen: () => {
      fullscreenRef.current?.()
    }
  }))

  return (
    <div>
      <canvas className="absolute top-0 left-0 h-full w-full" ref={canvasRef} />
    </div>
  )
})
export default CornerExpand

步骤2:父组件调用示例

import { useRef } from 'react'
import CornerExpand, { CornerExpandHandle } from './CornerExpand'

const ParentComponent = () => {
  const cornerExpandRef = useRef<CornerExpandHandle>(null)

  const handleClick = () => {
    // 调用子组件的fullscreen方法
    cornerExpandRef.current?.fullscreen()
  }

  return (
    <div>
      <button onClick={handleClick}>触发全屏动画</button>
      <CornerExpand ref={cornerExpandRef} />
    </div>
  )
}
export default ParentComponent

备选方案:通过props声明式触发

如果不想用命令式调用,也可以通过状态props触发,更符合React声明式的设计理念,适合调用频率不高的场景:

  1. 子组件新增triggerFullscreen布尔类型props
  2. 子组件新增useEffect监听该props变化,值为true时调用fullscreen方法
  3. 父组件点击按钮时翻转triggerFullscreen的状态即可触发

内容的提问来源于stack exchange,提问作者Niklas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 20:36:08