我已经使用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中编写类似上面的内容?
UPDATE
这是我最终转换模板的方式:
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的属性相同。 使用TypeScript,您需要定义自己的道具,如here中所示。如果您的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);