【发布时间】:2021-03-16 19:45:06
【问题描述】:
我正在使用 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 进行语法处理?
非常感谢!
【问题讨论】:
-
styles.$theme听起来这是个错字? props 的解构赋值使用theme(没有前导$符号)。应该是styles.theme,而不是基于这里的代码。
标签: reactjs typescript sass css-modules