Next.js番茄钟应用报错:传递的组件函数不是有效函数
解决React番茄钟组件传参时「SwitchStage is not a function」类型错误
问题根源
React组件的props是以单个对象的形式传入的,而非多个独立参数。你的Timer组件定义时错误地将props拆分为两个独立参数,导致实际拿到的第一个参数是完整的props对象,第二个参数为undefined,调用自然会触发类型错误。
修复步骤
- 修正组件参数接收方式
将Timer组件的参数改为对象解构形式,正确提取传递的函数:
// 错误写法 function Timer(SwitchStage,getTickingTime) { ... } // 正确写法 function Timer({ SwitchStage, getTickingTime }) { ... }
- 修正时间显示的错误写法
原代码中{()=>getTickingTime()}:00是将函数本身作为JSX内容渲染,不会执行函数获取返回值,需改为直接调用函数:
// 错误写法 <h1 className='font-bold m-0 text-9xl'> {()=>getTickingTime()}:00 </h1> // 正确写法 <h1 className='font-bold m-0 text-9xl'> {getTickingTime()}:00 </h1>
修复后的完整timer.tsx代码
import { ButtonsCard } from '@/components/ui/moveupbtn' import React from 'react' function Timer({ SwitchStage, getTickingTime }) { const options=["POMODORO","SHORT BREAK","LONG BREAK"] return ( <div className='min-h-screen flex-col lg:flex-row gap-10 lg:gap-0 justify-between items-center mt-20 md:mt-10 '> <div> <div className='min-w-xl mx-auto flex justify-center items-center gap-10'> { options.map((Option,idx)=>{ return( <div className=' flex items-center text-sm md:text-base '> <h1 key={idx} className={'hover:underline underline-offset-8 bg-opacity-20 transition-all duration-100 ease-in-out decoration-indigo-500 cursor-pointer' } onClick={()=> SwitchStage(idx)}> {Option} </h1> </div> ) }) } </div> </div> <div className='mt-10 mb-10 justify-center items-center flex min-h-[50vh]'> <h1 className='font-bold m-0 text-9xl'> {getTickingTime()}:00 </h1> </div> <div className='flex justify-center items-center'> <button className="shadow-[inset_0_0_0_2px_#616467] px-12 py-4 rounded-full tracking-widest uppercase font-bold bg-transparent hover:bg-[#616467] hover:text-white dark:text-neutral-200 transition duration-200"> STARt </button> </div> </div> ) } export default Timer
额外说明
- 组件定义时,若不使用解构,也可以通过
props.SwitchStage和props.getTickingTime的方式访问,但解构写法更简洁直观。 - 父组件
page.tsx中的函数定义没有问题,修复子组件接收方式即可解决报错。
内容的提问来源于stack exchange,提问作者Kenric Crasta Crken
相关产品推荐
相关产品推荐

