reactjs - React JSS 和 TypeScript
问题描述
我使用 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
任何成员。如果没有 TypeScript,你可能会“使用”很多类而不是定义它们,比如占位符;使用 TypeScript,他们都必须在那里;classes
render
- 在调用该
classnames
函数时,必须键入所有键。如果它们来自可能为 null 或未定义的变量,则必须添加as string
,否则将它们转换为字符串。除此之外,该className
属性的工作方式与没有 TypeScript 的情况相同。
解决方案
使用 TypeScript,您需要按照此处所示定义您的道具。如果你的 React 组件只需要render
方法,也推荐使用函数组件
对于您的情况,代码应如下所示:
import React from 'react';
import withStyles, { WithStyles } from 'react-jss';
import classNames from 'classnames';
const styles = theme => ({
root: {
}
});
interface IMyClassProps extends WithStyles<typeof styles> {
className: string;
}
const MyClass: React.FunctionComponent<IMyClassProps> = (props) => {
const { classes, className } = props;
return (
<div className={classNames({ [classes.root]: true, [className]: className})}>
</div>
);
};
export default withStyles(styles)(MyClass);
推荐阅读
- azure - 在 Azure Durable Functions Orchestator 中使用异步辅助函数是否安全?
- angular - 我想通过事件发射器为我的 html 输入设置值,并且在提交表单时这些值没有绑定。如何解决问题?
- c - 添加一段正常工作的代码时出现分段错误
- python-3.x - 模式识别和序列检测
- powershell - Foreach 循环错误地将文件添加到父文件夹
- kubernetes - 如何使用 shell 脚本在 Kubernetes 中手动对哪些组件进行故障排除
- string - 如何根据字符的相似程度定义两个字符串之间的距离?
- windows - 当我启用 VT-X(虚拟化技术)intel i5-3450 时 PC 崩溃
- r - 在 R 中按特定时间范围过滤
- python - 使用 split() python 打印前 3 个单词的第一个字母