问题
I would like to reproduce a grid from material-ui in react using typescript. A live demo can be found here.
I have adjusted the example to work with typescript such that my demo.jsx looks as:
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import FormLabel from '@material-ui/core/FormLabel';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import RadioGroup from '@material-ui/core/RadioGroup';
import Radio from '@material-ui/core/Radio';
import Paper from '@material-ui/core/Paper';
import {WithStyles} from "@material-ui/core/styles/withStyles";
const styles = (theme:any) => ({
root: {
flexGrow: 1,
},
paper: {
height: 140,
width: 100,
},
demo: {
height: 140,
width: 100,
},
control: {
padding: theme.spacing.unit * 2,
},
});
class App extends React.Component<WithStyles<typeof styles>> {
state = {
spacing: '16',
};
handleChange = (key:any) => (event:any, value:any) => {
this.setState({
[key]: value,
});
};
render() {
const { classes } = this.props;
const { spacing } = this.state;
return (
<Grid container className={classes.root} spacing={16}>
<Grid item xs={12}>
<Grid container className={classes.demo} justify="center" spacing={Number(spacing)}>
{[0, 1, 2].map(value => (
<Grid key={value} item>
<Paper className={classes.paper} />
</Grid>
))}
</Grid>
</Grid>
<Grid item xs={12}>
<Paper className={classes.control}>
<Grid container>
<Grid item>
<FormLabel>spacing</FormLabel>
<RadioGroup
name="spacing"
aria-label="Spacing"
value={spacing}
onChange={this.handleChange('spacing')}
row
>
<FormControlLabel value="0" control={<Radio />} label="0" />
<FormControlLabel value="8" control={<Radio />} label="8" />
<FormControlLabel value="16" control={<Radio />} label="16" />
<FormControlLabel value="24" control={<Radio />} label="24" />
<FormControlLabel value="32" control={<Radio />} label="32" />
<FormControlLabel value="40" control={<Radio />} label="40" />
</RadioGroup>
</Grid>
</Grid>
</Paper>
</Grid>
</Grid>
);
}
}
export default withStyles(styles)(App);
The problem is, that it throws the following error:
(101,79): Type 'number' is not assignable to type '0 | 8 | 16 | 24 | 32 | 40 | undefined'.
In the following line:
<Grid container className={classes.demo} justify="center" spacing={Number(spacing)}>
Any ideas? My first guess was that I need to typeset that spacing is of type number. As I am quite new to typescript, I could not find the right solution.
回答1:
It looks like Grid
accepts not any number, but a restricted set of numbers called GridSpacing
. See the type declaration 1 and 2. So after converting to a number as you did, you'll need to cast that number to a GridSpacing
:
<Grid container className={classes.demo} justify="center" spacing={Number(spacing) as GridSpacing}>
And add to your imports:
import { GridSpacing } from '@material-ui/core/Grid';
来源:https://stackoverflow.com/questions/51971705/reactjs-typescript-type-number-is-not-assignable-to-type-0-8-16-24-3