当我尝试在TypeScript中设置fontWeight
时出现此错误:
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...'.
即使400
是正确的数字,它也可以是任何数字,因此我得到错误,因为我理解它。我可以将此错误跟踪到指定fontWeight
应如下所示的React.CSSProperties:
fontWeight?: CSSWideKeyword | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
我无法设置test: React.CSSProperties
const styles = (theme: Theme) => ({
test: {
fontWeight: 400
}
});
我可以这样做,但不是Material UI处理类的方式。
const test: React.CSSProperties = {
fontWeight: 400
}
完整代码:
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>
);
}
}
答案 0 :(得分:10)
解决了它:
const styles = (theme: Theme) => ({
test: {
fontWeight: 400
} as React.CSSProperties
});
答案 1 :(得分:0)
当前接受的该问题的答案只是一种解决方法。解决此问题的正确方法是使用Material-UI中的createStyles
函数。
const styles = (theme: Theme) => createStyles({
test: {
fontWeight: 400
}
});