首页 > 解决方案 > 在 React 表中添加更多视图

问题描述

complete data我有一种情况,我frontend喜欢50 records

我必须在 中显示记录Table

有一次我只能show 10记录。然后我有view more按钮。click 查看更多. It will load the next 10 条记录`等等...

我可以得到一些帮助来解决这个问题吗?

表格代码:- 4 个组件 TableWrapper TableBodyTableHead TableRow

TableWrapper.js

const TableWrapper = ({...props}) => {
  const { tableData, columns } = props;
  const addNewRows = () => {
   console.log("Code for adding extra rows");
  }
  return (
    <table>
      <TableHead headers={columns} />
      <TableBody rows={tableData} tableData={tableData} headers={columns} />
    </table>
    <fragment onClick=addNewRows>View more</fragment>
  );
};

export default TableWrapper;

表体.js

const TableBody = ({...props}) => {
  const { rows, tableData, headers } = props;

  const [columnHeaderKeys, setColumnHeaderKeys] = useState([]);

  useEffect(()=>{
    let keysArray = [];
    headers.map((headKeys) =>{
      keysArray.push(headKeys.field)
    })
    {keysArray.length !== 0 ? setColumnHeaderKeys(keysArray) : setColumnHeaderKeys([])}
  },[])

  return (
    <>
    {tableData.length !== 0 ?
      tableData.data.firstResponse.map((row, index)=>{
        return (<tr key={index}><TableRow key={index} data={row} keys={columnHeaderKeys}/></tr>)
      }) : <div>{"No Data is there"}</div>
    }
    </>
  );
};

export default TableBody;

表头.js

const TableHead = ({...props}) => {
  const { headers } = props;
  return (
    <>
        {headers.map(header => (
          <th
            key={`table-header-${header.key}`}
            style={header.style}>
            {header.header}
          </th>
        ))}
    </>
  );
};

export default TableHead;

TableRow.js

const TableRow = ({...props}) => {
  const { keys, data } = props;

  return (
    <>
    {keys.map((key)=>{
        return <td key={props.data[key]}>{props.data[key]}</td>
    })}
    </>
  );
};

export default TableRow;

提前致谢

标签: javascriptreactjs

解决方案


假设tableData有所有行(50 条记录),您可以跟踪应该使用useState钩子显示的记录数。然后只需根据该值拉出您想要的行并将其交给表格。

像这样的东西:


const PAGE_SIZE = 10;

const TableWrapper = ({...props}) => {
  const { tableData, columns } = props;

  const [ numToDisplay, setNumToDisplay ] = useState(PAGE_SIZE);
  
  const addNewRows = () => {
    console.log("Code for adding extra rows");
    let newCount = numToDisplay + PAGE_SIZE;
    if (numToDisplay > tableData.length) {
      newCount = tableData.length;
    }
    setNumToDisplay(newCount)
  }

  const visibleData = tableData.slice(0, numToDisplay);
  
  return (
    <table>
    <TableHead headers={columns} />
    <TableBody tableData={visibleData} headers={columns} />
    </table>
    <fragment onClick=addNewRows>View more</fragment>
  );
};

我也不认为你需要这个rows道具,TableBody因为它tableData是一样的rows(从你的描述中我可以看出)。


推荐阅读