我收到的错误道具未定义

时间:2019-03-31 23:48:34

标签: reactjs

我正在尝试实现一个包含可交换项目网格的类,但是我在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);

2 个答案:

答案 0 :(得分:2)

问题是您应该使用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>
   );
}

答案 1 :(得分:0)

道具是类的参数,因此它们应该与它们一起使用。

const {classes} = this.props;

我认为这应该可以解决问题