reactjs - 使用 CSS 模块的 Typescript 道具和主题
问题描述
我正在使用 CSS 模块创建一个带有 typescript 的 react 组件库,以使项目变得简单,但是在主题化方面我正在努力使用 typescript 接口。我想为用户提供我的组件的几个变体,只需将属性更改为他想要的。
如果没有 CSS 模块,例如仅使用 SCSS,我可以在添加道具 className = 时使其工作,${styles.theme}
但是当我更改为模块时,它会停止工作,它不会再从 Button 重新配置界面属性。
像这样(Button.tsx):
import styles from "./Button.module.scss";
export interface ButtonProps {
/**
* Set this to change button theme properties
* @default primary
*/
theme:| "primary"
| "info"
| "success"
| "warning"
| "danger"
| "disabled"
| "primary-outline"
| "info-outline"
| "success-outline"
| "warning-outline"
| "danger-outline"
| "primary-flat";
onClick?: () => void;
}
export const Button: FunctionComponent<ButtonProps> = ({
children,
onClick,
theme,
...rest
}) => (
<div>
<button
className={`${styles.$theme}`}
onClick={onClick}
{...rest}
>
{children}
</button>
</div>
)
以及 CSS 模块文件(Button.module.scss):
button {
position: relative;
height: 1.75rem;
padding: 0.05rem .75rem;
display: inline-flex;
justify-content: center;
align-items: center;
font-size: 1rem;
text-align: center;
cursor: pointer;
user-select: none;
border: none;
border-radius: 4px;
border-width: 1px solid;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-transition: background 0.2s ease;
-moz-transition: background 0.2s ease;
-o-transition: background 0.2s ease;
transition: color 200ms ease-in 0s, border-color 200ms ease-in 0s, background-color 200ms ease-in 0s, filter 200ms ease-in 0s;
}
.primary {
background-color: $snow-04;
border-color: $snow-04;
color: $polar-night-04;
&:hover {
filter: brightness(90%);
}
}
.info {
background-color: $frost-02;
color: $polar-night-01;
&:hover {
filter: brightness(90%);
}
}
我该怎么做才能从 Button 界面访问主题道具和其他道具?如何在我的组件上对 className 进行语法处理?
非常感谢!
解决方案
Styles 毕竟是一个对象......您可以访问属性主题,例如:
<button className={styles[theme]} onClick={onClick} {...rest}>
{children}
</button>
我刚在这里试过:https ://codesandbox.io/s/typed-css-modules-8itfp?file=/src/App.tsx
推荐阅读
- reactjs - 我在 React 中使用道具时出现错误无法读取未定义的属性“地图”
- java - 从使用不同时区的日期计算时间
- c++ - c ++“错误:传递'const std :: vector
' 因为 'this' 参数丢弃了限定符 [-fpermissive]" - scala - 在构造函数的另一个参数的类型中引用依赖于路径的参数类型
- assembly - 为什么 rcx 在输入新标签时会刷新?
- kotlin - Kotlin,我怎样才能在这个意大利面条代码中缩短我的代码?
- excel - 在 Excel 中对多个条件进行排序和索引
- android - Android 10+ android.permission.NETWORK_STACK 用于隐藏 api
- r - R Jsonlite - 如何迭代 JSON 对象列表?
- c++ - 在天蓝色管道中分离构建和测试阶段的正确机制是什么?