问题描述
我正在使用 CSS 模块创建一个带有 typescript 的 react 组件库,以使项目变得简单,但是在主题化方面,我正在努力使用 typescript 接口。 我想为用户提供我的组件的几个变体,只需更改他想要的属性即可。
如果没有 CSS 模块,例如只使用 SCSS,我可以在添加 prop className = ${styles.theme}
时使其工作,但是当我更改为模块时,它停止工作,它不再重新调整界面属性来自按钮。
像这样(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 语法来这样做?
非常感谢!
解决方法
样式毕竟是一个对象...您可以访问属性主题,如:
<button className={styles[theme]} onClick={onClick} {...rest}>
{children}
</button>
我刚在这里试过:https://codesandbox.io/s/typed-css-modules-8itfp?file=/src/App.tsx