【发布时间】:2020-04-24 11:47:41
【问题描述】:
我使用 React 已经有一段时间了,现在我想改用 React 和 TypeScript。但是,我已经习惯了 JSS 样式(通过 react-jss 包),我不明白我应该如何将它们与 TypeScript 一起使用。我还使用 classnames 包,有条件地分配多个类名,我得到 TypeSCript 错误。
这是我的 React 组件模板:
import React, { Component } from 'react';
import withStyles from 'react-jss';
import classNames from 'classnames';
const styles = theme => ({
});
class MyClass extends Component {
render() {
const { classes, className } = this.props;
return (
<div className={classNames({ [classes.root]: true, [className]: className})}>
</div>
);
}
};
export default withStyles(styles)(MyClass);
我只是在学习 TypeScript,所以我什至不确定我是否理解我遇到的错误。我将如何在 TypeScript 中编写类似上述内容?
更新
这是我最终转换模板的方式:
import React from 'react';
import withStyles, { WithStylesProps } from 'react-jss';
import classNames from 'classnames';
const styles = (theme: any) => ({
root: {
},
});
interface Props extends WithStylesProps<typeof styles> {
className?: string,
}
interface State {
}
class Header extends React.Component<Props, State> {
render() {
const { classes, className } = this.props;
return (
<div className={classNames({ [classes.root as string]: true, [className as string]: className})}>
</div>
);
}
};
export default withStyles(styles)(Header);
注意事项:
- 定义
styles对象时,classes的任何成员在render方法中引用都必须定义。如果没有 TypeScript,你可能会“使用”很多类而不是定义它们,比如占位符;使用 TypeScript,他们都必须在那里; - 在调用
classnames函数时,必须键入所有键。如果它们来自可能为空或未定义的变量,您必须添加as string,否则将它们转换为字符串。除此之外,className属性的工作方式与没有 TypeScript 的情况相同。
【问题讨论】:
-
你能分享一个你遇到的错误的例子吗?
-
@casieber 我认为它们没有意义。我找不到任何关于使用 TypeScript 的 React JSS 的参考资料,并在我偶然发现它们时试图“修复”它们。所以大部分错误可能是我尝试了错误的解决方案造成的。
标签: reactjs typescript jss