我想使用打字稿在反应中重现grid from material-ui。可以在线观看演示here。
我已将示例调整为与打字稿一起使用,以使我的demo.jsx看起来像:
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);
问题是,它引发了以下错误:
(101,79): Type 'number' is not assignable to type '0 | 8 | 16 | 24 | 32 | 40 | undefined'.
在以下行中:
<Grid container className={classes.demo} justify="center" spacing={Number(spacing)}>
有什么想法吗?我的第一个猜测是,我需要排版设置间隔为数字类型。由于我刚接触打字稿,因此找不到正确的解决方案。