You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Winwheel库callbackFinished回调提示函数未定义问题求助

问题解决方法

问题根源

你把callbackFinished设置成了字符串'alertPrize()',Winwheel会尝试在全局作用域执行这个函数,但alertPrize是组件内部定义的局部函数,不在全局作用域中,因此会提示“函数未定义”的错误。

修改方案

直接将callbackFinished的值改为函数引用(不要加引号和括号),同时调整代码顺序让函数定义在动画配置之前(保证作用域内可访问):

import React from 'react'
import Winwheel from 'winwheel'
import TweenMax from 'gsap'

const Roulette = ({ width, height, canvasId}) => {
    let winWheel = null
    const wheelData = {}
    
    // 先定义回调函数
    function alertPrize()
    {
        createWheel()
        let winningSegment = winWheel.getIndicatedSegment();
        alert("You have won " + winningSegment.text + "!");
    }

    // 动画配置直接引用函数
    const animation = {
            'type': 'spinToStop',
            'duration': 5,
            'spins': 8,
            'easing': 'Power2.easeInOut',
            'callbackFinished': alertPrize // 直接传函数引用,无需引号和括号
    }

    wheelData['animation'] = animation

    const startAnimation = () => {
        winWheel = null
        createWheel()
        winWheel.startAnimation()
    }

    const createWheel = () => {
        if (typeof window !== 'undefined' && winWheel == null) {
            winWheel = new Winwheel(wheelData)
        }
    }

    createWheel()

    return (
        <div>
            <canvas id={canvasId} width={width} height={height} className='z-0'>
                Canvas not supported
            </canvas>
            <button onClick={startAnimation} className='absolute w-full h-full top-0'></button>
        </div>
    )
}

原理说明

直接传递函数引用时,Winwheel会在组件的局部作用域内调用该函数,能够正常访问到组件内部定义的alertPrize以及winWheel变量,避免了全局作用域查找失败的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:08:09