reactjs - 如何在 React 项目中扩展 `CSSProperties`

标签 reactjs typescript

我来自javascript世界和新手 typescript .我有一个用 typescript 编写的 React 项目.我声明了一个内联样式,但在 React 组件中使用它时收到以下警告:

Type '{ color: string; fontSize: string; fontWeight: number; }' is not assignable to type 'CSSProperties'.

下面是样式声明的代码。

const styles = {
    promAlert: {
        display: 'flex',
        flexDirection: 'column'
    }
};

下面是使用它的代码。这条线发出警告 <div style={styles.promAlert}> .

<div style={styles.promAlert}>
    {alert.substring('promotions.'.length)}
</div>

我搜索过这可能是由CSSProperties引起的在 react 中定义。我可能需要扩展此类并在其上添加更多属性。我想知道如何在我的项目中做到这一点。

另一个问题是为什么CSSProperties不包括所有受支持的 css 键。

最佳答案

TypeScript 需要特定的类型 "flex""column",但无需任何额外工作,它会接收到这两种类型的 string,这是太宽且没有描述性。你可以看到同样的错误发生在这里:

declare const value: string
const a: "a" = value // errors, `string` can't be assigned to the more specific `"a"`

这里有一些解决方案。我认为最优雅的是 as const,因此它将您的对象值视为它们的特定文字类型。还要确保您的 TS 版本是最新的才能使用它。

const styles = {
    promAlert: {
        display: 'flex',
        flexDirection: 'column',
    },
} as const

或者,您可以单独声明您的样式对象,并让它们通过 CSSProperties 接口(interface)进行类型检查。这为每个属性提供了自动完成功能,但这不能(轻松地)作为一个完整的对象来完成。

const promptAlert: React.CSSProperties = {
    display: 'flex',
    flexDirection: 'column'
}

// you can re-assign all of your styles into a single object if you want,
// but I think it would be easier to access `promptAlert` directly at this point
const styles = {
  promptAlert,
}

其他不太理想的解决方案:

  • { [key: string]: React.CSSProperties }:这不会对每个样式的名称执行类型检查,因此您可以执行 styles.abcdef没有任何错误

  • 将每个样式转换为 React.CSSProperties:这不会捕获样式本身的错误,例如你可能打错了 display: "fleex"

关于reactjs - 如何在 React 项目中扩展 `CSSProperties`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50960084/

相关文章:

html - 使用 typeScript 滚动到我的 webView 上的 x,y 坐标

javascript - 如何使用 Webpack 5 加载服务 worker ?

javascript - 将类切换到 .map() 函数中的特定项目

javascript - 在 React 中,根据数组中对象的值将状态作为数组返回

reactjs - Fetch API 无法加载,cors

javascript - 开发用于替换文本的 vscode 扩展

reactjs - 如何从antd中的数据动态创建列?

html - 是否有类似安全导航运算符的东西可以用于数组?

javascript - 属性在装饰器中未定义

typescript - 强制正确使用属性(property)