簡體   English   中英

反應地圖以用行呈現

[英]React map to render with row

嗨,我有一個包含 6 個元素的數組,並通過將數組划分為三個元素來使用 map 函數在每行中迭代 3 個元素,我不會在不划分數組的情況下執行此操作,我的代碼如下

<div
style={{
  width: "100%",
  display: "flex",
  flexWrap: "wrap",
  justifyContent: "space-around",
}}
>
{array1.map((item, index) => {
  return (
      <div className="col-4">
        <img  src={item.icon} />
        <p >{item.title}</p>
        <p >
          {item.description}
        </p>
      </div>
  );
})}
</div>
<div
style={{
  width: "100%",
  display: "flex",
  flexWrap: "wrap",
  justifyContent: "space-around",
}}
>
{array2.map((item) => {
  return (
    <div className="col-4 item-item">
      <img src={item.icon} />
      <p>{item.title}</p>
      <p>
        {item.description}
      </p>
    </div>
  );
})}
</div>

我想每行映射 3 個元素,而不將 6 個元素數組划分為 3 個元素,感謝您的建議

我建議您在此處使用此函數將數組拆分為多個塊。 從那里您可以執行嵌套地圖!

// # Source https://github.com/30-seconds/30-seconds-of-code/blob/master/snippets/chunk.md
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );

console.log(chunk([1, 2, 3, 4, 5,6], 3));
// Output - [[1,2,3],[4,5,6]]

考慮到您已經知道數組的長度為 6。假設數組名稱為“originalArray”

<div
style={{
  width: "100%",
  display: "flex",
  flexWrap: "wrap",
  justifyContent: "space-around",
}}
>
{originalArray.map((item, index) => {
(index<3)?
  return (
      <div className="col-4">
        <img  src={item.icon} />
        <p >{item.title}</p>
        <p >
          {item.description}
        </p>
      </div>
}
   : return( <div className="col-4 item-item">
      <img src={item.icon} />
      <p>{item.title}</p>
      <p>
        {item.description}
      </p>
    </div>)
  );
})}
</div>

您可以為此目的使用地圖

array.map((element, index) => {
        if (index % 3 === 0)
          return (
            <div className="row">
              <div className="col">{array[index]}</div>
              <div className="col">{array[index + 1]}</div>
              <div className="col">{array[index + 2]}</div>
            </div>
          );
      })

如果您決定更改每行的元素數,則只需調整值即可。

在此處檢查工作示例

我不確定這個片段的性能,但你可以用reduce而不是map來實現你想要的

array.reduce<JSX.Element[]>((rows, item, itemIndex) => {
    const ComponentToRender = <Component />
    if (itemIndex % 3 === 0) {
        rows.push(<Row key={rows.length + 1}>{ComponentToRender}</Row>);
    } else {
        const LastRow = rows[rows.length - 1];
        const cols = [
            ...React.Children.toArray(LastRow.props.children),
            ComponentToRender,
        ];
        rows[rows.length - 1] = <Row key={rows.length + 1}>{cols}</Row>;
    }
    
    return rows;
}, [])

或者只是使用 CSS 網格系統來渲染每行 3 個元素。 這樣你就可以堅持使用簡單的map

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM