jcu*_*bic 9 jsx typescript reactjs tsx
我想这样定义jsx:
<table style={{'--length': array.lenght}}>
<tbody>
<tr>{array}</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
并且我在CSS中使用--length,也有一些单元格具有--count,它们使用css伪选择器(使用Counter hack)显示计数。
但打字稿显示错误:
TS2326: Types of property 'style' are incompatible.
Type '{ '--length': number; }' is not assignable to type 'CSSProperties'.
Object literal may only specify known properties, and ''--length'' does not exist in type 'CSSProperties'.
Run Code Online (Sandbox Code Playgroud)
是否可以更改样式属性的类型以接受CSS变量(自定义属性),或者是否可以对样式对象进行强制?
min*_*lid 65
您可以简单地将使用字符串模板的模块声明合并放在文件顶部或任何 .d.ts 文件中,然后您将能够使用任何 CSS 变量,只要它以“--”开头,即字符串或数字
import 'react';
declare module 'react' {
interface CSSProperties {
[key: `--${string}`]: string | number
}
}
Run Code Online (Sandbox Code Playgroud)
例如
<div style={{ "--value": percentage }} />
Run Code Online (Sandbox Code Playgroud)
Car*_*era 17
您可以向变量添加类型断言。IE {['--css-variable' as any]: value }
<table style={{['--length' as any]: array.lenght}}>
<tbody>
<tr>{array}</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
ixr*_*ock 15
像这样:
render(){
var style = { "--my-css-var": 10 } as React.CSSProperties;
return <div style={style}>...</div>
}
Run Code Online (Sandbox Code Playgroud)
HaN*_*riX 15
尝试:
<table style={{['--length' as string]: array.lenght}}>
...
</table>
Run Code Online (Sandbox Code Playgroud)
Ben*_*uer 12
强制转换styletoany违背了使用 TypeScript 的全部目的,因此我建议React.CSSProperties使用您的自定义属性集进行扩展:
import React, {CSSProperties} from 'react';
export interface MyCustomCSS extends CSSProperties {
'--length': number;
}
Run Code Online (Sandbox Code Playgroud)
通过扩展React.CSSProperties,您将使 TypeScript 的属性检查保持活动状态,并且您将被允许使用您的自定义--length属性。
使用MyCustomCSS看起来像这样:
const MyComponent: React.FC = (): JSX.Element => {
return (
<input
style={
{
'--length': 300,
} as MyCustomCSS
}
/>
);
};
Run Code Online (Sandbox Code Playgroud)
如果转到的定义CSSProperties,则会看到:
export interface CSSProperties extends CSS.Properties<string | number> {
/**
* The index signature was removed to enable closed typing for style
* using CSSType. You're able to use type assertion or module augmentation
* to add properties or an index signature of your own.
*
* For examples and more information, visit:
* https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors
*/
}
Run Code Online (Sandbox Code Playgroud)
该链接提供了如何通过增加Propertiesin 的定义csstype或将属性名称强制转换为来解决类型错误的示例any。
小智 5
import "react";
type CustomProp = { [key in `--${string}`]: string };
declare module "react" {
export interface CSSProperties extends CustomProp {}
}
Run Code Online (Sandbox Code Playgroud)
将其放入您的 global.d.ts 文件中
| 归档时间: |
|
| 查看次数: |
6779 次 |
| 最近记录: |