【问题标题】:Creating dynamic cards from an array从数组创建动态卡片
【发布时间】:2019-06-06 16:43:03
【问题描述】:

我正在尝试使用相同的组件创建 3 个,标题为“month 1”、“month 2”和“month 3”的卡片包含一个表格,我需要为数组中的每张卡片添加一个标题。

我尝试使用属性来遍历数组,并且我已经在 3 张卡片中填充了 3 个表,但我无法填充标题

App.JS

function App() {
  const months = ['month 1', 'month 2', 'month 3'];
  return (
    <div className='App'>
      <NavBar/>
      <>
        {months.map(month => <SimpleCard> {month}</SimpleCard>)}
      </>
      <Container>
        <Button variant="contained" color="primary" className='submitButton' id='submitButton'>
          Submit
        </Button>
      </Container>
    </div>

  );
}


card.JS

export default function SimpleCard() {
  const classes = useStyles();
  return (
    <Card className={classes.card}>
      <CardContent>
        <Typography className={classes.title} variant="h5" component="h2">
          {/*This is where the month should be displayed*/}

        </Typography>
        <Typography variant="body2" component="p">
          <Table/>
        </Typography>
      </CardContent>
    </Card>
  );
}

我需要将月份显示在卡片内的表格上方

【问题讨论】:

    标签: arrays reactjs dynamic material-ui react-props


    【解决方案1】:

    所以只要接受孩子身上的道具,并渲染传递给组件的孩子

    export default function SimpleCard(props) {
      const classes = useStyles();
      return (
        <Card className={classes.card}>
          <CardContent>
            <Typography className={classes.title} variant="h5" component="h2">
              {props.children}
            </Typography>
            <Typography variant="body2" component="p">
              <Table/>
            </Typography>
          </CardContent>
        </Card>
      );
    }
    

    不过,对于您的用例,我认为将标题作为明确的标题道具传递会更好

    {months.map(month => <SimpleCard title={month} />)}
    

    并渲染它

    {props.title}
    

    【讨论】:

      猜你喜欢
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 2019-02-13
      • 2022-11-04
      • 1970-01-01
      • 2018-01-23
      相关资源
      最近更新 更多