材质UI Texboxes动态创建的窗体Array Disply多列ReactJs

时间:2020-04-28 07:05:03

标签: javascript reactjs material-ui

我从API获取汽车列表,我有以下代码来创建标签列表,并用文本框编辑汽车代码。

  {!carQuery.loading &&
            carDefinitions?.map((car: ICarType, idx: number) =>
                <TextField
                    required
                    id={car.name}
                    label={car.name}
                    defaultValue={car.code}
                    name={car.name}
                    key={idx}
                    onChange={e => {
                        const code = carDefinitions.filter(x => x.name === e.target.name);
                        shortCut[0].code = e.target.value;
                    }}
                />)

我遇到的问题是可能有超过50辆汽车,所以表格的确很长,任何想法都比一个较长的表格(例如专栏或分页)更容易实现。我不确定什么是最好的

interface ICarType
{
    name: string;
    code: string;
    isDiesel: boolean;
}

1 个答案:

答案 0 :(得分:1)

使用Material-UI实验室的分页(了解更多Here

我创建了一个PaginationComponent迭代对象数组并对其进行分页。该组件使用两个道具才能正常工作

  1. items-您要迭代的对象数组
  2. itemsPerPage-页面上显示的项目数

注意

在此分页示例中,我将您的<TextField/>组件与问题中提供的道具一起使用。

我还修改了onChange组件上<TextField/>的处理程序,以便在沙箱中工作。

请根据您的需要调整代码,这只是演示分页如何工作的MVP

沙盒here

const PaginationComponent = ({ items, itemsPerPage }) => {
  const [page, setPage] = useState(0);
  const handleChangePage = useCallback((e, v) => setPage(v - 1), []);

  return (
    <Grid container direction="column" justify="center" alignItems="stretch">
      <Grid item>
        {items
          .slice(page * itemsPerPage, page * itemsPerPage + itemsPerPage)
          .map((car, idx) => (
            <TextField
              required
              fullWidth
              id={car.name}
              label={car.name}
              defaultValue={car.code}
              name={car.name}
              key={idx}
              onChange={e => console.log(e.target)}
            />
          ))}
      </Grid>
      <Grid item>
        <Pagination
          count={Math.ceil(items.length / itemsPerPage)}
          onChange={handleChangePage}
        />
      </Grid>
    </Grid>
  );
};