React 및 typescript의 스타일 속성에 css 변수를 정의하는 방법
jsx를 다음과 같이 정의합니다.
<table style={{'--length': array.lenght}}>
<tbody>
<tr>{array}</tr>
</tbody>
</table>
CSS에서 --length를 사용하고 있습니다.또한 CSS 의사 셀렉터를 사용하여 카운트를 표시하는 --count를 가진 셀도 있습니다(카운터 해크를 사용).
그러나 typescript는 오류를 발생시킵니다.
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'.
CSS 변수(커스텀 속성)를 받아들이도록 스타일 속성 유형을 변경할 수 있습니까? 아니면 On style 객체를 강제할 수 있는 방법이 있습니까?
다음과 같이 합니다.
function Component() {
const style = { "--my-css-var": 10 } as React.CSSProperties;
return <div style={style}>...</div>
}
또는 추가 비용 없이style변수:
function Component() {
return <div style={{ "--my-css-var": 10 } as React.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
*/
}
이 페이지는 의 정의를 확대함으로써 유형 오류를 해결하는 방법의 예를 보여줍니다.Properties에csstype또는 속성명을 지정한다.any.
변수에 유형 어설션을 추가할 수 있습니다. {['--css-variable' as any]: value }
<table style={{['--length' as any]: array.length}}>
<tbody>
<tr>{array}</tr>
</tbody>
</table>
캐스팅:style로.anyTypeScript를 사용하는 목적 전체를 무효로 하기 때문에,React.CSSProperties커스텀 속성 세트:
import React, {CSSProperties} from 'react';
export interface MyCustomCSS extends CSSProperties {
'--length': number;
}
확장으로React.CSSPropertiesTypeScript의 속성 체크를 활성 상태로 유지하고 커스텀을 사용할 수 있습니다.--length소유물.
사용.MyCustomCSS다음과 같습니다.
const MyComponent: React.FC = (): JSX.Element => {
return (
<input
style={
{
'--length': 300,
} as MyCustomCSS
}
/>
);
};
이 모듈 선언 병합은 문자열 템플릿을 사용하여 파일 맨 위 또는 임의의 .d.ts 파일에 넣을 수 있습니다.그러면 CSS 변수가 '--'로 시작하는 한 문자열 또는 숫자입니다.
import 'react';
declare module 'react' {
interface CSSProperties {
[key: `--${string}`]: string | number
}
}
예를들면
<div style={{ "--value": percentage }} />
import "react";
type CustomProp = { [key in `--${string}`]: string };
declare module "react" {
export interface CSSProperties extends CustomProp {}
}
이것을 global.d.ts 파일에 저장합니다.
를 사용하여 다른 접근 방식을 추가하고 싶다.document.body.style.setPropertycss 변수가 특정 소품에 의해 영향을 받는 경우 해당 변수를 css에 넣을 수 있습니다.useEffect다음과 같습니다.
useEffect(() => {
document.body.style.setProperty(
"--image-width-portrait",
`${windowSize.width - 20}px`
);
}, [windowSize])
나중에 css 파일 내에서 다음과 같이 호출할 수 있습니다.
width: var(--image-width-portrait);
시험:
<table style={{['--length' as string]: array.lenght}}>
<tbody>
<tr>{array}</tr>
</tbody>
</table>
언급URL : https://stackoverflow.com/questions/52005083/how-to-define-css-variables-in-style-attribute-in-react-and-typescript
'programing' 카테고리의 다른 글
| React.js 앱의 모든 오류를 try/catch 블록으로 잡을 수 있습니까? (0) | 2023.04.04 |
|---|---|
| NSJON Serialization을 통해 JSON에 null 값을 포함하려면 어떻게 해야 합니까? (0) | 2023.04.04 |
| 인터페이스를 사용하여 클래스를 시리얼화하려면 어떻게 해야 합니까? (0) | 2023.04.04 |
| Angular JS 및 웹 워커 (0) | 2023.04.04 |
| WordPress를 사용하여 제거할 때 테이블을 드롭하는 방법 (0) | 2023.04.04 |