gpt4 book ai didi

reactjs - React 中内联 fontWeight 样式期间的 Typescript 错误

转载 作者:搜寻专家 更新时间:2023-10-30 21:02:24 24 4
gpt4 key购买 nike

我正在尝试在 td

上实现此 css 规则
const boldText = {
fontWeight: 'bold'
}

<td style={boldText}>Content</td>

但它抛出以下错误:

[ts]
Type '{ style: { fontWeight: string; }; children: string; }' is not assignable to type 'DetailedHTMLProps<TdHTMLAttributes<HTMLTableDataCellElement>, HTMLTableDataCellElement>'.
Type '{ style: { fontWeight: string; }; children: string; }' is not assignable to type 'TdHTMLAttributes<HTMLTableDataCellElement>'.
Types of property 'style' are incompatible.
Type '{ fontWeight: string; }' is not assignable to type 'CSSProperties'.
Types of property 'fontWeight' are incompatible.
Type 'string' is not assignable to type '"bold" | "initial" | "inherit" | "unset" | "normal" | "bolder" | "lighter" | 100 | 200 | 300 | 40...'.

最佳答案

Typescript 有时会非常愚蠢。它将 fontWeight 的类型推断为字符串,即使它可以将其缩小到其精确的文字。您可以将其转换为自身来解决此问题:

const boldText = {
fontWeight: 'bold' as 'bold'
}

<td style={boldText}>Content</td>

现在您还可以使用新的 as const declaration在你的文字的末尾以获得相同的效果:

const boldText = {
fontWeight: 'bold'
} as const;

<td style={boldText}>Content</td>

最后,您始终可以在声明对象时为其提供显式类型:

const boldText: React.CSSProperties = {
fontWeight: "bold"
};

<td style={boldText}>Content</td>

关于reactjs - React 中内联 fontWeight 样式期间的 Typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48087015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com