同一TSX文件中如何传props:Scale组件传width到Color组件报错如何解决
问题修复方案
存在的3个核心错误
- width变量作用域错误:你在
if/else块内部用let声明width,let存在块级作用域,出了if/else代码块后变量会被销毁,外部无法访问。 - React组件参数规则错误:React函数组件仅支持接收唯一的props对象作为入参,你给Color组件定义的第二个参数
props无法接收到自定义传值。 - map调用未传递自定义参数:直接调用
colors.map(Color)只会传入数组元素、下标两个默认参数,不会把width参数传入Color组件。
修正后完整代码
import React from 'react'; // 提前定义Color组件的props类型,符合TS规范 interface ColorProps { color: string; width: number; } const Color = (props: ColorProps) => ( <div style={{ backgroundColor: props.color, width: props.width, height: 15, display: 'inline-block', }} /> ); const Scale = (props: { brewer: string; Length: number }) => { const brewer = props.brewer; const Length = props.Length; // 把width声明提到if/else块外部,提升作用域 let width: number; if (Length === 0) { width = 1; } else { width = Math.floor(120 / Length); console.log(width); } const colors = getColors(chroma.scale(brewer), LENGTH); return ( <div> <div style={{ width: 30, fontSize: '1.5em', textAlign: 'right', display: 'flex', flexDirection: 'column', }} > {brewer} </div> {/* 显式渲染Color组件,传递需要的参数,注意加key属性避免React警告 */} {colors.map((color, index) => ( <Color key={index} color={color} width={width} /> ))} </div> ); };
额外说明
- 补充了TS类型定义,替换原有的
any类型,避免后续类型错误 - 新增了React组件必须的
key属性,解决遍历渲染的React警告 - 把宽松相等
==替换为严格相等===,避免隐式类型转换导致的逻辑错误
内容的提问来源于stack exchange,提问作者Nishtha Sharma
相关产品推荐
相关产品推荐

