Sim*_*one 6 typescript reactjs jss
我已经使用 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);
Run Code Online (Sandbox Code Playgroud)
我刚刚学习 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);
Run Code Online (Sandbox Code Playgroud)
要记住的事情:
styles对象时,必须定义方法classes中引用的任何成员。如果没有 TypeScript,您可能会“使用”大量类而不定义它们,就像占位符一样;对于 TypeScript,它们都必须在那里;renderclassnames函数时,必须键入所有键。如果它们来自可能为 null 或未定义的变量,则必须添加as string, 否则将它们转换为字符串。除此之外,该className属性的工作方式与没有 TypeScript 时相同。使用 TypeScript,您需要定义您的 props,如下所示。render如果你的 React 组件只需要方法,也建议使用函数组件
对于您的情况,代码应如下所示:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4985 次 |
| 最近记录: |