我已经使用React很长一段时间了,现在我想切换到使用。然而,我已经习惯了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对象时,必须定义在render方法中引用的classes的任何成员。没有TypeScript,您可以“使用”许多类,而不是像占位符那样定义它们;使用TypeScript,它们都必须存在;classnames函数时,必须键入所有键。如果它们来自可能为null或未定义的变量,则必须添加as string,否则必须将它们转换为字符串。除此之外,className属性的工作方式与没有TypeScript的情况相同。发布于 2020-01-07 00:15:32
使用TypeScript,您需要定义您的道具,如这里所示。如果您的recommended只需要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);https://stackoverflow.com/questions/59620481
复制相似问题