iT邦幫忙

0

react如何操作每一張card

  • 分享至 

  • xImage

我現在有很多資料 然後用map的方式把資料取出
如下 會有很多張卡片(我是用material-ui的card)

https://ithelp.ithome.com.tw/upload/images/20210216/20120704qhtnCTuFQ2.png
點擊打開
https://ithelp.ithome.com.tw/upload/images/20210216/20120704PXv6Bm2NrF.png

現在有一個問題是 我按下去後 每一張卡片都會被打開
請問如果我想 只打開某一張卡片的內容該怎麼做呢

  const [expanded, setExpanded] = React.useState(false);

  const handleExpandClick = () => {
    setExpanded(!expanded);
  };

        <IconButton
          className={clsx(classes.expand, {
            [classes.expandOpen]: expanded,
          })}
          onClick={handleExpandClick}
          aria-expanded={expanded}
          aria-label="show more"
        >

上面是文件提供的程式碼

froce iT邦大師 1 級 ‧ 2021-02-17 08:41:30 檢舉
你 expanded 是一個共通變數(state)吧?
簡單一點是去檢查class裡有沒有 expandOpen 這個 className。
一樣寫在 handleExpandClick 裡就好。

react我不熟,實際的code請自己寫。
感覺是structure 的問題
你應該要list.map(<Card />)
然後再在Card 內的useState update吧

如果你已經是這樣, 那可以試試<Card /> 內加key attribute
e.g. <Card key={id} />

中文不好的話抱歉. 我是香港的.
Luis-Chen iT邦新手 4 級 ‧ 2021-02-17 22:10:03 檢舉
vincent 的是最佳解
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
Floralt 昀翰
iT邦新手 4 級 ‧ 2021-02-17 08:49:47

雖然我沒寫 react 但這個問題我覺得十之八九要用 id 解
請指定要觸發的 id

froce iT邦大師 1 級 ‧ 2021-02-17 09:14:53 檢舉

不用,這不需要用id。
在前端框架中要用到id去解通常是沒辦法的時候。

2
froce
iT邦大師 1 級 ‧ 2021-02-17 09:28:41

大概會是像下面的樣子,實際上能不能動我不清楚,但大致上就是透過傳遞event去取得目前點擊的class裡有沒有"expandOpen"這個class

  const [expanded, setExpanded] = React.useState(false);

  const handleExpandClick = (e) => {
    const expandedState = e.target.className.includes("expandOpen")
    setExpanded(!expandedState);
  };

        <IconButton
          className={clsx(classes.expand, {
            [classes.expandOpen]: false,
          })}
          onClick={handleExpandClick(e)}
          aria-expanded={false}
          aria-label="show more"
        >


熟悉react的應該可以用 bind 和 this 來解。

0
wet452010
iT邦見習生 ‧ 2021-02-25 16:58:29

卡片 封装成一个独立组件 每个组件的状态是独立的 例如:

我要發表回答

立即登入回答