首页 > 解决方案 > 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);

要记住的事情:

标签: reactjstypescriptjss

解决方案


使用 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);

推荐阅读