如何修复 React 应用程序中半径设置的类型警告
How to fix type warning for radius settings in React app
我有一个使用 recharts 绘制条形图的 React 应用程序。我使用一个函数来检查数据并决定是否圆角单元格。看起来像下面这样:
function customizedCell(this: { column: number; color: string }, entry, index, array) {
// Logic to determine which corners to round.
return <Cell key={index} fill={this.color} radius={[0, 30, 30, 0]} />;
}
它是从 React 组件内部调用的,如下所示:
<Bar dataKey="mykey" stackId="1">
{this.data.map(customizedCell, { column: 3, color: '#AABBCC' })}
</Bar>
一切正常,但是当我 运行 使用 npm 的应用程序时,半径值数组中的每个数字都会出现如下警告:
TS2322: Type 'number' is not assignable to type 'string'.
如何避免此警告? radius={'[0, 30, 30, 0]'}
、radius={'0 30 30 0'}
等会断码(无舍入效果)。
要解决您的类型问题,您可以先将每个值放在引号中,将它们从数字转换为字符串:30 => '30'。
但是,之后 radius
属性会出现类型错误。要解决这个问题,您可以将其类型转换为 unknown
,然后再转换为 string
以移除类型警告。
两项更改应如下所示:
return <Cell key={index} fill={this.color} radius={['0', '30', '30', '0'] as unknown as string} />;
我有一个使用 recharts 绘制条形图的 React 应用程序。我使用一个函数来检查数据并决定是否圆角单元格。看起来像下面这样:
function customizedCell(this: { column: number; color: string }, entry, index, array) {
// Logic to determine which corners to round.
return <Cell key={index} fill={this.color} radius={[0, 30, 30, 0]} />;
}
它是从 React 组件内部调用的,如下所示:
<Bar dataKey="mykey" stackId="1">
{this.data.map(customizedCell, { column: 3, color: '#AABBCC' })}
</Bar>
一切正常,但是当我 运行 使用 npm 的应用程序时,半径值数组中的每个数字都会出现如下警告:
TS2322: Type 'number' is not assignable to type 'string'.
如何避免此警告? radius={'[0, 30, 30, 0]'}
、radius={'0 30 30 0'}
等会断码(无舍入效果)。
要解决您的类型问题,您可以先将每个值放在引号中,将它们从数字转换为字符串:30 => '30'。
但是,之后 radius
属性会出现类型错误。要解决这个问题,您可以将其类型转换为 unknown
,然后再转换为 string
以移除类型警告。
两项更改应如下所示:
return <Cell key={index} fill={this.color} radius={['0', '30', '30', '0'] as unknown as string} />;