React+TypeScript中父组件向类子组件传递props报错问题咨询
报错原因
- 你的父组件是函数式组件,React 函数组件内部不存在
this关键字,直接使用this.startTimeInSeconds会抛出未定义错误。 - 你当前的父组件中没有定义
startTimeInSeconds变量,即便不使用this也会找不到对应值。
修复方案
1. 基础父传子 Props 传递实现
按照以下代码修改父组件即可解决当前报错,实现父组件向子组件传值:
import '../css/App.css'; import * as React from "react"; import Child from "./ChildComponent" function App() { // 定义要传递给子组件的倒计时初始值 const startTimeInSeconds = 10; return ( <> <div> <Child startTimeInSeconds = {startTimeInSeconds} /> </div> </> ); } export default App;
2. 子组件向父组件传值实现
如果需要子组件把内部状态(比如剩余倒计时时长、倒计时结束事件)传递给父组件,可以通过父传子的回调函数实现:
步骤1:修改子组件 Props 类型,新增回调字段
type Props = { startTimeInSeconds: number; // 新增回调函数,用于向父组件传递剩余时间 onTimeChange?: (remaining: number) => void; // 可选:倒计时结束的回调 onTimeEnd?: () => void; }
步骤2:子组件状态变化时触发回调
修改子组件的decrementTimeRemaining方法:
decrementTimeRemaining = () => { if (this.state.timeRemainingInSeconds > 0) { const newTime = this.state.timeRemainingInSeconds - 1 this.setState({ timeRemainingInSeconds: newTime }); // 向父组件传递最新的剩余时间 this.props.onTimeChange?.(newTime) } else { clearInterval(this.timer!); // 触发倒计时结束回调 this.props.onTimeEnd?.() } };
步骤3:父组件接收子组件传递的数据
修改父组件,传入对应的回调函数即可:
import '../css/App.css'; import * as React from "react"; import Child from "./ChildComponent" function App() { const startTimeInSeconds = 10; // 接收子组件传递的剩余时间 const handleTimeChange = (remaining: number) => { console.log('当前剩余倒计时:', remaining) } // 接收子组件的倒计时结束事件 const handleTimeEnd = () => { console.log('倒计时已结束') } return ( <> <div> <Child startTimeInSeconds={startTimeInSeconds} onTimeChange={handleTimeChange} onTimeEnd={handleTimeEnd} /> </div> </> ); } export default App;
额外注意事项
你当前的子组件没有在卸载时清理定时器,可能触发内存泄漏警告,建议在子组件中新增生命周期方法:
componentWillUnmount() { clearInterval(this.timer) }
内容的提问来源于stack exchange,提问作者christheliz
相关产品推荐
相关产品推荐

