首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Mui/DataGrid设置/获取自定义筛选器组件中的筛选值

Mui/DataGrid设置/获取自定义筛选器组件中的筛选值
EN

Stack Overflow用户
提问于 2022-10-19 15:35:21
回答 2查看 194关注 0票数 1

如何在mui/DataGrid托管人设置值中看到onFilterModelChange中的设置值?

我有密码:

代码语言:javascript
运行
复制
function MyFilterPanel() {
  const apiRef = useGridApiContext();
 
  const handleDateChange = () => {
    const { state, setState, forceUpdate } = apiRef.current;
    setState({
        filterModel: {
          items: [{ columnField: 'quantity', operatorValue: '>', value: 10000 }],
        },
    });
  };
  return (
    <DateRangePicker
      onChange={handleDateChange}
    />
  );
}
 // and
<DataGrid
    ...
        filterMode="server"
        onFilterModelChange={(newValue) => {
            console.log(newValue);
        }}
        components={{
            FilterPanel: MyFilterPanel,
        }}
/>

我有错误:

TypeError: Cannot read properties of undefined (reading 'columnVisibilityModel')

编辑。我添加了我的代码,以显示我想如何使用它。https://codesandbox.io/s/datagrid-forked-2ulvnu

如何使用:

  1. 点击...
  2. 拾取滤波器
  3. 采摘日期范围
代码语言:javascript
运行
复制
import * as React from "react";
import DateRangePicker from "rsuite/DateRangePicker";
import { DataGrid, useGridApiContext } from "@mui/x-data-grid";
import "./ui.css"; // @import "rsuite/dist/rsuite.css";

function DateRangePickerFilterPanel() {
  const apiRef = useGridApiContext();

  const handleDateChange = (value) => {
    // I want set here values for previous and next date
  };
  return <DateRangePicker onChange={handleDateChange} />;
}

const rows = [
  { id: "2020-01-02", col1: "Hello" },
  { id: "2020-01-03", col1: "MUI X" },
  { id: "2020-01-04", col1: "Material UI" },
  { id: "2020-01-05", col1: "MUI" },
  { id: "2020-01-06", col1: "Joy UI" },
  { id: "2020-01-07", col1: "MUI Base" }
];

const columns = [
  { field: "id", headerName: "DateTime", type: "dateTime", width: 150 },
  { field: "col1", headerName: "Column 1", width: 150 }
];

export default function App() {
  const [dates, setDates] = React.useState({});

  /*
  const getAllNames = () => {
    axiosInstance.get(`${API_PATH}/api/names?startDate=${dates.startDate}&endDate=${dates.endDate}`)
      .then((response) => {
        ...
      })
      .catch((error) => console.error(`Error: ${error}`));
  };
  */
  return (
    <div style={{ height: 300, width: "100%" }}>
      <DataGrid
        rows={rows}
        pagination
        columns={columns}
        paginationMode="server"
        rowsPerPageOptions={[10]}
        filterMode="server"
        onFilterModelChange={(newValue) => {
          // And here I want to get that data to be able
          // to pas it to backend request or somehow have acces
          // to it in fucntion App()
          console.log(newValue);
          // setDates({
          //   startDate: newValue[0],
          //   endDate: newValue[1].toISOString()
          // });
        }}
        components={{
          FilterPanel: DateRangePickerFilterPanel
        }}
      />
    </div>
  );
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-22 00:09:39

UPDATE:给出了OP的说明,说明他们没有使用MUI DataGridPro,而是使用服务器端筛选,下面是一个解决方案:

如果我对你的理解是正确的,那么你似乎正在努力完成以下工作:

  1. 从套件/DateRangePicker获取开始日期和结束日期,
  2. 使用DataGrid中的服务器端筛选来过滤结果。

对于#1,我们可以通过将DateRangePickerFilterPanel处理程序函数作为支柱来捕获onChange以外的日期值。您可以使用自定义筛选面板,并使用DataGrid的组件和DataGrid属性将处理程序函数作为支柱传递给它。

代码语言:javascript
运行
复制
function DateRangePickerFilterPanel(props) {
  // Instead of handling a date change here, pass the handler in as a prop.
  // This allows you access to the selected values in App. You could also use
  // a state management library like redux, but that is not shown here.
  return <DateRangePicker onChange={props.onChange} />;
}

export default function App() {
  const [dates, setDates] = useState()

  const handleDateChange = (newValue) => {
    // update local state with the new values
    setDates(newValue);
  }

  return (
    <DataGrid
      rows={rows}       // defined elsewhere
      columns={columns} // defined elsewhere
      components={{
        FilterPanel: DateRangePickerFilterPanel,
      }}
      componentsProps={{
        filterPanel: { onChange: handleDateChange }
      }}
    >
    </DataGrid>
  );
}

第二,每当更新筛选日期时,我们都要调用服务器。我们将“日期”存储在反应状态,每次更新这些日期时,我们都可以使用useEffect钩子调用服务器。

代码语言:javascript
运行
复制
export default function App() {
  const [dates, setDates] = useState()

  useEffect( () => {
    // call the server here
  }, [dates]);
}

注意:服务器端文档这里表示您需要使用onFilterModelChange处理程序,但在这种情况下这是不必要的,因为您使用的是自定义筛选面板。我们可以触发DateRangePicker的更新,并且不需要使用onFilterModelChange。

以下是包含评论的完整解决方案:

代码语言:javascript
运行
复制
import * as React from "react";
import { DateRangePicker } from "rsuite";
import { DataGrid, GridFilterModel } from "@mui/x-data-grid";
import "./ui.css";
import { fakeAxios } from "./server";

function DateRangePickerFilterPanel(props) {
  // Instead of handling a date change here, pass the handler in as a prop.
  // This allows you access to the selected values in App. You could also use
  // a state management library like redux, but that is not shown here.
  return <DateRangePicker onChange={props.onChange} />;
}

const columns = [
  { field: "id", headerName: "ID", width: 150 },
  { field: "created", headerName: "DateTime", type: "date", width: 150 },
  { field: "col1", headerName: "Column 1", width: 150 }
];

export default function App() {
  // These are the selected values in the date range picker. To use server
  // side filtering they must be sent to the server, and the server returns
  // the filtered dataset.
  const [dates, setDates] = React.useState({});

  // Store the row data for the data table in react state. This will be updated
  // when you call the server API with filter parameters.
  const [rows, setRows] = React.useState([]);

  // Here is where we handle the date change in the filter panel. Set the dates
  // state so it can be used by the server API.
  const handleDateChange = (newValue) => {
    setDates(newValue);
  };

  // The rows for the datatable are loaded from the server using the dates as
  // a filter. This useEffect runs (and calls the server) every time the value
  // of 'dates' changes.
  React.useEffect(() => {
    fakeAxios
      .get(`/api/names?startDate=${dates[0]}&endDate=${dates[1]}`)
      .then((response) => {
        console.log(
          `server called with filter; returned ${response.length} records`
        );
        setRows(response);
      });
  }, [dates]);

  return (
    <div style={{ height: 500, width: "100%" }}>
      <DataGrid
        rows={rows}
        pagination
        columns={columns}
        paginationMode="server"
        rowCount={10}
        rowsPerPageOptions={[10, 100]}
        filterMode="server"
        
        // onFilterModelChange is not needed since we are using a custom filter
        // panel.

        components={{
          FilterPanel: DateRangePickerFilterPanel
        }}
        componentsProps={{
          filterPanel: { onChange: handleDateChange }
        }}
      />
    </div>
  );
}

我用'fakeAxios‘对象来模拟服务器响应。它不像在实际服务器中那样过滤数据,而是只返回随机数量的记录。

有关更多细节,请参见完整的代码沙箱:https://codesandbox.io/s/datagrid-forked-version2-koz9cy?file=/src/App.tsx

原来的答案:

tl;博士

  1. GridApi是一个专业的特性--使用DataGridPro而不是DataGrid
  2. 使用useGridApiRef()钩子(而不是useGridApiContext()钩子)从网格组件外部访问GridApi

这里的主要问题是,GridApi是一个支持/高级特性,将在DataGridPro上工作,而不是DataGrid。文档对此并不十分清楚(通过他们自己的承认:https://github.com/mui/mui-x/issues/2904#issuecomment-945436602)。在用于DataGrid的API文档中,apiRef属性不可用,但它存在于DataGridPro上。

第二个问题是您应该使用的是useGridApiRef()而不是useGridApiContext()。基本上,useGridApiRef()用于从数据网格外部访问GridApi,而useGridApiContext()用于从数据网格中访问GRidApi (它们提供了详细的这里解释)

下面是完成您要寻找的内容的代码:

代码语言:javascript
运行
复制
import { useState } from "react";
import { DataGridPro, useGridApiRef } from "@mui/x-data-grid-pro";
import { DateRangePicker, LocalizationProvider } from "@mui/x-date-pickers-pro";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import { AdapterDayjs } from "@mui/x-date-pickers-pro/AdapterDayjs";
import "./styles.css";

export default function App() {
  const [value, setValue] = useState([null, null]);
  const gridApi = useGridApiRef();

  const rows = [
    { id: 1, col1: "Hello", col2: "World", quantity: 5000 },
    { id: 2, col1: "DataGridPro", col2: "is Awesome", quantity: 5000 },
    { id: 3, col1: "MUI", col2: "is Amazing", quantity: 12000 }
  ];

  const columns = [
    { field: "col1", headerName: "Column 1", width: 150 },
    { field: "col2", headerName: "Column 2", width: 150 },
    { field: "quantity", headerName: "Quantity", width: 150, type: "number" }
  ];

  const handleDateChange = (newValue) => {
    setValue(newValue);

    if (gridApi.current) {
      gridApi.current.setFilterModel({
        items: [
          {
            columnField: "quantity",
            operatorValue: ">",
            value: "10000"
          }
        ]
      });
    }
  };

  return (
    <div className="App" style={{ height: "300px" }}>
      <h1>Hello CodeSandbox</h1>
      <LocalizationProvider dateAdapter={AdapterDayjs}>
        <DateRangePicker
          value={value}
          onChange={handleDateChange}
          renderInput={(startProps, endProps) => (
            <>
              <TextField {...startProps} />
              <Box sx={{ mx: 2 }}> to </Box>
              <TextField {...endProps} />
            </>
          )}
        ></DateRangePicker>
      </LocalizationProvider>
      <DataGridPro
        apiRef={gridApi}
        rows={rows}
        columns={columns}
        onFilterModelChange={(newValue) => {
          console.log(`received filter mode change: ${newValue}`);
          console.log(newValue);
        }}
      ></DataGridPro>
    </div>
  );
}

这里的代码沙箱:https://codesandbox.io/s/stackoverflow-mui-datagrid-ehxesp

票数 1
EN

Stack Overflow用户

发布于 2022-10-22 23:20:08

我假设您希望从DateRangePicker获取日期并将它们传递给您的API调用。一旦用户选择了dateRange,然后再次填充数据集(假设基于filterMode设置为server)。我更新了你的密码。请查收。因为你没有使用梅的FilterModel,所以你不需要onFilterModelChange道具。

代码语言:javascript
运行
复制
import DateRangePicker from "rsuite/DateRangePicker";
import { DataGrid} from "@mui/x-data-grid";
import "./ui.css";

const getAllNames = (startDate, endDate)=> {
  console.log(startDate, endDate);
 //  Add your API call here
};

function DateRangePickerFilterPanel() {
 const handleDateChange = (value) => {
   getAllNames(value[0], value[1]);
 };
 return <DateRangePicker onChange={handleDateChange} />;
};

const rows = [
  { id: "2020-01-02", col1: "Hello" },
  { id: "2020-01-03", col1: "MUI X" },
  { id: "2020-01-04", col1: "Material UI" },
  { id: "2020-01-05", col1: "MUI" },
  { id: "2020-01-06", col1: "Joy UI" },
  { id: "2020-01-07", col1: "MUI Base" }
];

const columns = [
  { field: "id", headerName: "DateTime", type: "dateTime", width: 150 },
  { field: "col1", headerName: "Column 1", width: 150 }
];

export default function App() {
  /*
  const getAllNames = () => {
    axiosInstance.get(`${API_PATH}/api/names?startDate=${dates.startDate}&endDate=${dates.endDate}`)
      .then((response) => {
        ...
      })
      .catch((error) => console.error(`Error: ${error}`));
  };
  */
 
  return (
    <div style={{ height: 300, width: "100%" }}>
      <DataGrid
        rows={rows}
        pagination
        columns={columns}
        paginationMode="server"
        rowsPerPageOptions={[10]}
        filterMode="server"
        components={{
          FilterPanel: DateRangePickerFilterPanel
        }}
      />
    </div>
  );
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74128123

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档