【问题标题】:How to control each card using react hooks如何使用反应钩子控制每张卡
【发布时间】:2021-02-18 05:33:05
【问题描述】:

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

有两张牌,

当我点击展开按钮时,两者同时打开

如何一键打开一张卡片?

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

这是我测试的代码。

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

【问题讨论】:

  • 你要么需要存储一个布尔数组,每张卡片一个,指示卡片本身是否打开。或者另一种方法是创建一个卡片组件并在其中有一个状态,因此每张卡片都有自己的内部状态来控制自身的开放性(这是假设您不需要知道卡片是展开还是不在父级中)
  • @Jayce444 谢谢!我会尝试第二种解决方案。

标签: reactjs react-hooks material-ui


【解决方案1】:

一个简单的解决方案是存储扩展卡的索引值,然后根据存储在扩展状态的索引值传递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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多