TypeScript 2.4.1 - > fontWeight - >类型'number'不能赋值为'"inherit"| 400 |

Ogg*_*las 5 javascript css typescript material-design material-ui

我尝试fontWeight在TypeScript中设置时出现此错误:

Types of property 'test' are incompatible.
    Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>'.
        Types of property 'fontWeight' are incompatible.
            Type 'number' is not assignable to type '"inherit" | 400 | "initial" | "unset" | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 30...'.
Run Code Online (Sandbox Code Playgroud)

即使400是正确的数字,它也可以是任何数字,因此我得到错误,因为我理解它.我可以将此错误跟踪到React.CSSProperties,它指定fontWeight应该如下所示:

fontWeight?: CSSWideKeyword | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
Run Code Online (Sandbox Code Playgroud)

我不能做的就是设定 test: React.CSSProperties

const styles = (theme: Theme) => ({
    test: {
        fontWeight: 400
    }
});
Run Code Online (Sandbox Code Playgroud)

我可以这样做,但不是Material UI处理类的方式.

const test: React.CSSProperties = {
    fontWeight: 400
}
Run Code Online (Sandbox Code Playgroud)

完整代码:

import * as React from "react";
import * as ReactDOM from "react-dom";
import * as ReactRouter from "react-router";
import { withRouter } from "react-router-dom";
import { withStyles } from 'material-ui/styles';
import Badge from 'material-ui/Badge';
import Grid from 'material-ui/Grid';
import { Theme } from 'material-ui/styles';

interface IState {
    userName: string;
}

interface IProps {
    history?: any;
    classes?: any;
}

const styles = (theme: Theme) => ({
    test: {
        fontWeight: 400
    }
});

class Menu extends React.Component<IProps, IState> {
    constructor(props: IProps) {
        super(props);
        this.state = {
            userName: localStorage.userName ? 'userName ' + localStorage.userName : "",
        }
    }
    render() {
        return (
            <div>
                <Grid container spacing={24}>
                    <Grid item xs={12} className={this.props.classes.test}>
                    <span>Test</test>
                    </Grid>
                </Grid>
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

Ogg*_*las 10

解决了它:

const styles = (theme: Theme) => ({
    test: {
        fontWeight: 400
    } as React.CSSProperties
});
Run Code Online (Sandbox Code Playgroud)


pio*_*ros 7

目前接受的这个问题的答案只是一个解决方法。解决这个问题的正确方法是使用createStylesMaterial-UI 中的函数。

const styles = (theme: Theme) => createStyles({
    test: {
        fontWeight: 400
    }
});
Run Code Online (Sandbox Code Playgroud)

请参阅材质 UI 文档