我正在将功能组件更改为 class 组件,但遇到了问题。 更新代码后,我的 scss 不见了。 在将我的功能组件重构为 class 组件之前,一切都在 scss 中正常工作,但就像我什至没有在我的 index.js 中导入 styles.scss 文件一样。 但正如您所见,它是进口的。 ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我使用 TypeScript 在 React 中构建了一个简单的Panel.tsx
组件:
import * as React from 'react';
import { Label, LabelType } from 'components/basic';
import styles from './Panel.module.scss';
interface IPanel {
title?: string;
children: React.ReactNode;
}
const Panel = ({ title, children }: IPanel) => {
return (
<div className={styles.main}>
{title && <Label type={LabelType.Title} bold text={title} />}
{children}
</div>
);
};
export default Panel;
这是配套的Panel.module.scss
文件:
.main {
border: 2px solid $black;
border-radius: 10px;
padding: 10px;
}
现在,如果我想将 SCSS 类注入到Panel
中,可能带有color
、 background-color
、 font-size
等。有没有办法做到这一点?
是的,以接受className
属性的方式编写组件是很常见的(但必须由组件作者明确地将其应用于组件根)。 例如, material-ui
的所有组件都接受一个类名(我不是 material-ui 的忠实粉丝,但至少在这方面他们做得对)。
您可以将其显式添加到您的道具类型
interface IPanel {
title?: string;
children: React.ReactNode;
className?: string;
}
...并在您的组件中使用它
import classnames from 'clsx'; // this is a popular package to combine classnames
const Panel = ({ title, children, className }: IPanel) => {
return (
<div className={classnames(styles.main, className)}>
{title && <Label type={LabelType.Title} bold text={title} />}
{children}
</div>
);
};
...或者您可以使用 React 中的一种实用程序类型。 例如,我经常只允许将所有常见的 HTML 属性和子属性添加为道具(是的,我知道,我的类型并不太精确)
import type { FunctionComponent, HTMLAttributes } from 'react';
export type CommonPropsFunctionComponent<TProps = {}> = FunctionComponent<
TProps & HTMLAttributes<Element>
>;
import { CommonPropsFunctionComponent } from './types';
interface IPanel {
title?: string;
}
const Panel: CommonPropsFunctionComponent<IPanel> = ({ title, children, className }) => {
return (
<div className={classnames(styles.main, className)}>
{title && <Label type={LabelType.Title} bold text={title} />}
{children}
</div>
);
};
使用扩展运算符
您可能很想在这里使用它; 但请注意:您必须小心不要意外覆盖您自己的本地类名。 为了说明这一点,在这个例子中:
tabIndex
可以被覆盖className
列表不能被覆盖,只能扩展const SomeComponent= ({ children, className, ...rest }) => {
return (
<div tabIndex={0} {...rest} className={classnames(styles.root, className)}>
{children}
</div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.