我试图实现一个包含可交换项目网格的类,但我得到的错误道具没有在render()之后的行中定义。我很反应,我希望能够实现这个类,以便我可以在以后添加删除和添加功能。
import React, { Component } from 'react';
import Swappable from './components/SwappableComponent'
import './App.css';
import DataTable from './components/tableWidget';
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";
const styles = theme => ({
root: {
flexGrow: 1
},
paper: {
padding: theme.spacing.unit * 2,
textAlign: "center",
color: theme.palette.text.secondary
}
});
class App extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
}
componentDidUpdate() {
}
render() {
const { classes } = props;
return (
<div className={classes.root}>
<Grid container spacing={24}>
<Grid item xs={12} sm={6}>
<Paper className={classes.paper}><Swappable id='1' content={<DataTable/>}/></Paper>
</Grid>
<Grid item xs={12} sm={6}>
<Paper className={classes.paper}> <Swappable id='2' content="#2"/></Paper>
</Grid>
<Grid item xs={12} sm={6}>
<Paper className={classes.paper}><Swappable id='3' content="#3"/></Paper>
</Grid>
<Grid item xs={12} sm={6}>
<Paper className={classes.paper}><Swappable id='4' content="#4"/></Paper>
</Grid>
</Grid>
</div>
);
}
}
App.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(App);
问题是你应该使用this.props
而不仅仅是props
。改变
const { classes } = props;
至
const { classes } = this.props;
编辑
关于你的评论,你可以像这样构建你的状态:
constructor(props){
super(props)
this.state = {
papers: [
{
id: 1,
content: <DataTable />
xs: 12,
sm: 6,
},
{
id: 2,
content: "#2",
xs: 12,
sm: 6,
},
// All the other papers
]
{
}
然后,渲染网格如下:
render() {
const { classes } = this.state;
return (
<div className={classes.root}>
<Grid container spacing={24}>
{this.state.papers.map(paper => (
<Grid item xs={paper.xs} sm={paper.sm}>
<Paper className={classes.paper}><Swappable id={paper.id} content={paper.content}/></Paper>
</Grid>
</Grid>
</div>
);
}
道具是一个类的参数,所以他们应该与他们一起。
const {classes} = this.props;
我认为这应该可以解决问题