You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何按指定矩阵格式渲染二维数组为表格UI

React Native 实现特定顺序的矩阵表格渲染

问题描述

我有一个4行12列的二维数组,需要在React Native中渲染成表格样式的UI。当前的渲染逻辑是直接按原数组的行横向渲染,但输出顺序不符合预期:

原数组:

const arr2d = [
  ["3", "4", "9", "10", "15", "16", "21", "22", "27", "28", "33", "34"],
  ["2", "5", "8", "11", "14", "17", "20", "23", "26", "29", "32", "35"],
  [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "36"],
  ["1", "6", "7", "12", "13", "18", "19", "24", "25", "30", "31", "37"],
];

当前实现的渲染函数:

seats = () => {
  let arr2d = this.state.selectedSeatLayouts.reduce((r, {column, row, name }) => {
    if (!r[row]) r[row] = [];
    r[row][column] = name;
    return r;
  }, []);
  return (
    arr2d.map((o, i) => {
      return(
        <View style={{ flexDirection: 'row' }} key={i}>
          { o.map((e, i) =>{
            return(
              <View style={{flex: 1}} key={i}>
                <Text>{e}</Text>
              </View>
            )
          }) }
        </View>
      )
    })
  );
}

当前渲染结果(行内顺序):
3 4 9 10 15 16 21 22 27 28 33 34
2 5 8 11 14 17 20 23 26 29 32 35
undefined... undefined 36
1 6 7 12 13 18 19 24 25 30 31 37

期望的元素渲染顺序(按表格横向排列):
1 2 3 6 5 4 7 8 9 12 11 10
13 14 15 18 17 16 19 20 21 24 23 22
25 26 27 30 29 28 31 32 33 ... ... ...
37 36 35 34 ... ... ... ... ... ... ...


解决方案

核心思路是先按照期望的规则重新排列元素顺序,再渲染成表格。具体来说:

  1. 对大部分列,按第3行 → 第1行 → 第0行的顺序取元素;
  2. 第11列(最后一列)需要包含第2行的元素,按第3行 → 第2行 → 第1行 → 第0行的顺序取;
  3. 把所有列的元素按顺序拼接成一维数组,再拆分成4行保持表格结构。

修改后的代码:

seats = () => {
  // 从state生成原二维数组
  const arr2d = this.state.selectedSeatLayouts.reduce((r, {column, row, name }) => {
    if (!r[row]) r[row] = [];
    r[row][column] = name;
    return r;
  }, []);

  // 标准化数组为4行12列,补全缺失的undefined
  const normalizedArr = Array(4).fill().map((_, rowIdx) => {
    const row = arr2d[rowIdx] || [];
    return Array(12).fill().map((_, colIdx) => row[colIdx]);
  });

  // 根据列索引返回要取的行顺序
  const getRowPriority = (colIdx) => {
    // 最后一列包含第2行的36,所以行顺序特殊处理
    if (colIdx === 11) return [3, 2, 1, 0];
    // 其他列取第3、1、0行的元素
    return [3, 1, 0];
  };

  // 生成符合期望顺序的一维元素数组
  const orderedElements = [];
  for (let col = 0; col < 12; col++) {
    const rowOrder = getRowPriority(col);
    rowOrder.forEach(rowIdx => {
      const seatValue = normalizedArr[rowIdx][col];
      if (seatValue !== undefined) {
        orderedElements.push(seatValue);
      }
    });
  }

  // 把一维数组拆分为4行,每行12个元素(不足补空)
  const renderedRows = Array(4).fill().map((_, rowIdx) => {
    const start = rowIdx * 12;
    return orderedElements.slice(start, start + 12);
  });

  // 渲染表格
  return (
    renderedRows.map((row, rowKey) => (
      <View 
        style={{ 
          flexDirection: 'row', 
          marginVertical: 4, 
          justifyContent: 'space-around' 
        }} 
        key={rowKey}
      >
        {row.map((seat, colKey) => (
          <View 
            style={{ 
              flex: 1, 
              borderWidth: 1, 
              padding: 8, 
              alignItems: 'center',
              marginHorizontal: 2
            }} 
            key={colKey}
          >
            <Text>{seat || ''}</Text>
          </View>
        ))}
      </View>
    ))
  );
}

代码说明

  • normalizedArr:确保原数组是标准的4行12列,避免因某些行/列缺失导致的渲染异常;
  • getRowPriority:根据列的位置定义行的读取顺序,适配最后一列的特殊元素;
  • orderedElements:遍历所有列,按规则收集元素,生成期望的序列;
  • renderedRows:将一维序列拆分为4行,保持原表格的行数结构;
  • 额外添加了边框、内边距等样式,让表格结构更直观,你可以根据需求调整样式细节。

内容的提问来源于stack exchange,提问作者hellodevs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:52:48