TSX组件类型错误:缺失必填属性onChange,求解决方案
解决React TypeScript构建错误:Step组件缺少onChange属性
错误信息
/components/Lane.tsx:37:18
Type error: Property 'onChange' is missing in type '{ key: string; value: StepModel; }' but required in type 'StepProps'.
问题根源
Step组件的StepProps接口明确要求传入onChange回调函数,但在Lane组件渲染Step时,仅传递了key和value属性,未提供onChange。同时,部分模型类的状态更新方法存在逻辑错误,导致无法正确生成新的实例。
分步修复
1. 给Lane组件中的Step传递onChange回调
修改/components/Lane.tsx中的renderSteps函数,为Step添加onChange回调,当Step状态变化时,更新Lane的steps数组并触发上层状态更新:
function renderSteps() { return lane.steps.map((step, i) => { return ( <Step key={`${step.id}-${i}`} value={step} onChange={(newStep) => { // 生成新的steps数组,替换当前修改的step const updatedSteps = lane.steps.map((s, index) => index === i ? newStep : s ); // 创建新的Lane实例并调用上层onChange props.onChange(new LaneModel(lane.id, lane.description, updatedSteps, lane.selected)); }} /> ); }); }
2. 修复StepModel的状态更新逻辑
StepModel的alternarSelecao和abrir方法未正确传递新的selected值,修改/model/step.ts:
alternarSelecao() { const selecionada = !this.selected; return new StepModel(this.id, this.value, selecionada); // 替换原this.selected为selecionada } abrir() { const aberta = true; return new StepModel(this.id, this.value, aberta); // 替换原this.selected为aberta }
3. 给Home组件中的Lane传递onChange回调
Lane组件的LaneProps要求传入onChange,修改index.js(建议改为index.tsx):
import React, { useState } from 'react'; import Lane from '../../components/Lane' import LaneModel from '../../model/lane' import StepModel from '../../model/step' export default function Home() { const [lane, setLane] = useState(new LaneModel(400,"Health", [ StepModel.inactive(700, "Imports Data"), StepModel.inactive(701, "Cleans Data"), StepModel.inactive(702, "Creates Notebook"), StepModel.active(703, "Trains Model") ], true)); return( <div style={{display: "flex"}}> <Lane value={lane} onChange={(newLane) => setLane(newLane)} /> </div> ); }
4. 修复LaneModel的状态更新逻辑
LaneModel的alternarSelecao和abrir方法同样存在参数错误,修改/model/lane.ts:
alternarSelecao() { const selected = !this.selected; return new LaneModel(this.id, this.description, this.steps, selected); // 替换原this.selected为selected } abrir() { const aberta = true; return new LaneModel(this.id, this.description, this.steps, aberta); // 替换原this.selected为aberta }
完成以上修改后,重新执行npm run build即可消除类型错误,同时组件的状态更新逻辑将正常工作。
内容的提问来源于stack exchange,提问作者Carlos Ferreira
相关产品推荐
相关产品推荐

