如何使用反应钩子控制每张卡片

时间:2021-02-18 05:33:05

标签: reactjs react-hooks material-ui

我正在尝试使用 material-ui 进行反应

有两张牌,

当我点击展开按钮时,它们同时打开

如何一键打开一张卡片?

我知道是因为当它 setExpanded 时,所有的 item 都会被设置, 我已经尝试添加密钥,但它仍然不起作用。

这是我测试的代码。

https://stackblitz.com/edit/react-kwexep?file=src%2FApp.js

1 个答案:

答案 0 :(得分:3)

一个简单的解决方案是存储扩展卡片的索引值,然后根据扩展状态存储的索引值传递expanded prop。

export default function App() {
  let data=[{
      id:1,
      title:"2"
    },
    {
      id:2,
      title:"3"
    }]
    
const classes = useStyles();
  const [expanded, setExpanded] = React.useState(false);

  const handleExpandClick = (index) => {
    expanded === index ? setExpanded(null) : setExpanded(index)
  };

  return (
    data.map((i,index)=>(
    <Card className={classes.root} >
      <CardActions disableSpacing>
        <IconButton
          className={clsx(classes.expand, {
            [classes.expandOpen]: expanded ===index,
          })}
          onClick={()=>handleExpandClick(index)}
          aria-expanded={expanded === index}
          aria-label="show more"
        >
          <ExpandMoreIcon />
        </IconButton>
      </CardActions>
      <Collapse in={expanded===index} timeout="auto" unmountOnExit>
        <CardContent>
          <Typography paragraph>     </Typography>
          <Typography paragraph>
            {i.title}
          </Typography>
        </CardContent>
      </Collapse>
    </Card>

    ))
  );
}

这是工作演示:https://stackblitz.com/edit/react-yyycsr?file=src%2FApp.js