跳至主要内容

静态类型

样式属性类型

StyleX 完全支持静态类型。最常用的实用程序类型是 StyleXStyles,用于接受任何任意 StyleX 样式。

import type {StyleXStyles} from '@stylexjs/stylex';
import * as stylex from '@stylexjs/stylex';

type Props = {
...
style?: StyleXStyles,
};

function MyComponent({style, ...otherProps}: Props) {
return (
<div
{...stylex.props(localStyles.foo, localStyles.bar, style)}
>
{/* ... */}
</div>
);
}
禁止动态样式

StaticStyles 可以代替 StyleXStyles 来接受任意静态样式,但禁止动态样式。

约束可接受的样式

可以使用类型参数与 StyleXStyles<{...}> 配合使用,以限制可接受的样式。

从一组样式属性中接受

要将可接受的样式属性限制为给定集合,可以使用具有允许属性的对象类型

import type {StyleXStyles} from '@stylexjs/stylex';

type Props = {
// ...
style?: StyleXStyles<{
color?: string;
backgroundColor?: string;
borderColor?: string;
borderTopColor?: string;
borderEndColor?: string;
borderBottomColor?: string;
borderStartColor?: string;
}>;
};

现在,style 属性将仅接受定义的属性,而不允许任何其他属性。

良好的默认样式

最佳实践是使样式类型的键可选,并在组件本身中设置基线样式。

TypeScript 可能不会捕获额外的样式属性

当给定具有额外属性的对象时,TypeScript 对象类型不会报错。我们已采取措施来缓解此问题,但在某些极端情况下,您可能能够传入额外的、不允许的样式而不会出现类型错误。

限制样式的可能值

除了可接受的样式属性外,还可以约束这些属性的值。

import type {StyleXStyles} from '@stylexjs/stylex';

type Props = {
...
// Only accept styles for marginTop and nothing else.
// The value for marginTop can only be 0, 4, 8 or 16.
style?: StyleXStyles<{
marginTop: 0 | 4 | 8 | 16
}>,
};

现在,此组件仅接受具有 marginTop 属性且没有其他属性的样式。marginTop 的值只能是 04816 之一。

禁止属性

有时定义黑名单比定义白名单更方便。

import type {StyleXStylesWithout} from '@stylexjs/stylex';
import * as stylex from '@stylexjs/stylex';

type NoLayout = StyleXStylesWithout<{
position: unknown,
display: unknown,
top: unknown,
start: unknown,
end: unknown,
bottom: unknown,
border: unknown,
borderWidth: unknown,
borderBottomWidth: unknown,
borderEndWidth: unknown,
borderStartWidth: unknown,
borderTopWidth: unknown,
margin: unknown,
marginBottom: unknown,
marginEnd: unknown,
marginStart: unknown,
marginTop: unknown,
padding: unknown,
paddingBottom: unknown,
paddingEnd: unknown,
paddingStart: unknown,
paddingTop: unknown,
width: unknown,
height: unknown,
flexBasis: unknown,
overflow: unknown,
overflowX: unknown,
overflowY: unknown,
}>;

type Props = {
// ...
style?: NoLayout,
};

function MyComponent({style, ...}: Props) {
return (
<div
{...stylex.props(localStyles.foo, localStyles.bar, style)}
>
{/* ... */}
</div>
);
}

此处,对象类型中列出的属性将被禁止,但所有其他样式仍将被接受。