简体   繁体   English

如何在反应功能组件中的 AgGrid Cell 中添加按钮和下拉菜单

[英]How to add a button and a dropdown in AgGrid Cell in react Functional Component

I have list of data.我有数据列表。 I am using AgGrid in react to display this data list.我在反应中使用 AgGrid 来显示这个数据列表。 For each row i need to display a column having a delete button and a second column having a dropdown and a reset button.对于每一行,我需要显示具有删除按钮的列和具有下拉列表和重置按钮的第二列。

When i click the delete button i need the corresponding row data and when i click reset button i need the dropdown option select as well as the corresponding row data.当我单击删除按钮时,我需要相应的行数据,当我单击重置按钮时,我需要下拉选项 select 以及相应的行数据。

I have searched but i am not able to figure out how to do it in react functional components.我已经搜索过,但我无法弄清楚如何在反应功能组件中做到这一点。 I have found that i need to use ICellRendererReactComp but i am not sure how as i am new to react and AgGrid我发现我需要使用 ICellRendererReactComp 但我不确定我是如何反应和 AgGrid 的新手

My current code looks something like this:我当前的代码如下所示:

import React, { useState } from "react";
import toaster from "toasted-notes";

import { apiRequest, errorHandler } from "../../utilis/apiRequest";
import { columnDefsFromArr } from "../Threads/columnDefs";
import { AgGridReact, ICellRendererReactComp } from "ag-grid-react";
import { isResourcePresent } from "../../utilis/helper";

function Sessions(props) {
  const [email, setEmail] = useState("");
  const [reid, setReid] = useState(null);
  const [sessionsResp, setSessionsResp] = useState(null);
  const [columnDefs, setColumnDefs] = useState(null);
  const [rowData, setRowData] = useState(null);
  const defaultColDef = {
    sortable: true,
    filter: true,
    resizable: true,
  };
  const colsToExlude = ["requestId"];
  const resetSessionOptions = [
    "None",
    "ClearClientCache",
    "PasswordChange",
    "Suspended",
    "InvalidSession",
    "Expired",
  ];

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
  };

  const handleGetSession = () => {
    setReid(email);
    getSessions({ reid: email, env: props.env });
  };

  const getSessions = (data) => {
    console.log(data, reid);
    let isError = validateForm(data);
    if (isError.status) {
      apiRequest(
        props.sessionToken,
        "get_session",
        data,
        (res) => {
          if (res.status === 200) {
            console.log(res.data);
            setRowData(res.data.sessions);
            makeGrid(res.data);
          }
        },
        (err) => {
          errorHandler(err);
        }
      );
    } else {
      toaster.notify(isError.msg, {
        duration: 1500,
      });
    }
  };

  const handleDelete = (data) => {
    console.log(data);
  };

  const handleReset = (data) => {
    console.log(data);
  };

  const makeGrid = (data) => {
    let cols = [];
    data.sessions.map((ele) => {
      Object.keys(ele).map((key) => cols.push(key));
    });
    let localCols = [];
    if (isResourcePresent(props.resources, "del_session")) {
      localCols.push({
        headerName: "Delete Sessio",
      });
    }
    if (isResourcePresent(props.resources, "reset_session")) {
      localCols.push({
        headerName: "Reset Session"
      });
    }
    cols = [...new Set(cols)];
    colsToExlude.map((key) => {
      let ind = cols.indexOf(key);
      if (ind > -1) {
        cols.splice(ind, 1);
      }
    });
    let finalColDefs = [...localCols, ...columnDefsFromArr(cols)];
    console.log(finalColDefs);
    setColumnDefs(finalColDefs);
  };

  const validateForm = (data) => {
    if (data.reid.trim() === "") {
      return { status: false, msg: "Email/Email Id is reqd" };
    } else {
      return { status: true };
    }
  };

  return (
    <div className="container-fluid">
      <div>
        <h5>Get Sessions Information</h5>
      </div>

      <div className="card mt-2 p-3 bg-red shadow p-3 mb-5 bg-white rounded">
        <div className="row m-2">
          <div className="col-sm-6">
            <input
              type="text"
              className="form-control"
              value={email || ""}
              placeholder="Email / Email ID"
              onChange={handleEmailChange}
            />
          </div>
          <div className="col-sm-2">
            <button className="button btn-primary" onClick={handleGetSession}>
              Get Information
            </button>
          </div>
        </div>
      </div>
      {rowData == null ? null : (
        <div className="card mt-2 p-3 bg-red shadow p-3 mb-5 bg-white rounded">
          <div
            className="ag-theme-balham"
            style={{ height: "500px", width: "100%" }}
          >
            <AgGridReact
              columnDefs={columnDefs}
              rowData={rowData}
            ></AgGridReact>
          </div>
        </div>
      )}
    </div>
  );
}

export { Sessions };

  • handleDelete: this is the function i want to call when that delete button is clicked for some corresponding row, handleDelete:这是 function 我想在单击相应行的删除按钮时调用,
  • resetSessionOptions: this is the dropdown list options i need to display in second column along with Reset button. resetSessionOptions:这是我需要在第二列中显示的下拉列表选项以及重置按钮。
  • handleReset: this the function i want to call when that Reset button besides the dropdown is clicked for some corresponding row handleReset:这是 function 我想在单击下拉列表之外的某个相应行的重置按钮时调用

So I searched a lot and finally came across this example: https://stackblitz.com/edit/angular-ag-grid-button-renderer?file=src%2Fapp%2Frenderer%2Fbutton-renderer.component.ts所以我搜索了很多,最后发现了这个例子: https://stackblitz.com/edit/angular-ag-grid-button-renderer?file=src%2Fapp%2Frenderer%2Fbutton-renderer.component.ts

Above example is for Angular and uses classes.以上示例适用于 Angular 并使用类。

I figured out how to do it in react Functional Components.我想出了如何在反应功能组件中做到这一点。 I did not used any interface or something but implemented all methods in above given example and made Renderer classes for the two columns i needed.我没有使用任何接口或其他东西,但实现了上面给出的示例中的所有方法,并为我需要的两列创建了 Renderer 类。 You can see the code below.你可以看到下面的代码。

UPDATE: My this solution works but this is causing my all other state variables to reset to initial state.更新:我的这个解决方案有效,但这导致我的所有其他 state 变量重置为初始 state。 I am not sure why thats happening.我不确定为什么会这样。 I am looking for a solution for that.我正在为此寻找解决方案。

Session.js Session.js

import React, { useState } from "react";
import toaster from "toasted-notes";

import { apiRequest, errorHandler } from "../../utilis/apiRequest";
import { columnDefsFromArr } from "../Threads/columnDefs";
import { AgGridReact, ICellRendererReactComp } from "ag-grid-react";
import { isResourcePresent } from "../../utilis/helper";
import { ButtonRenderer } from "./ButtonRenderer";
import { DropDownRender } from "./DropDownRender";

function Sessions(props) {
  const [email, setEmail] = useState("");
  const [reid, setReid] = useState(null);
  const [sessionsResp, setSessionsResp] = useState(null);
  const [columnDefs, setColumnDefs] = useState(null);
  const [rowData, setRowData] = useState(null);
  const frameworkComponents = {
    buttonRenderer: ButtonRenderer,
    dropDownRenderer: DropDownRender,
  };
  const defaultColDef = {
    sortable: true,
    filter: true,
    resizable: true,
  };
  const colsToExlude = ["requestId"];
  const resetSessionOptions = [
    "None",
    "ClearClientCache",
    "PasswordChange",
    "Suspended",
    "InvalidSession",
    "Expired",
  ];

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
  };

  const handleGetSession = () => {
    setReid(email);
    getSessions({ reid: email, env: props.env });
  };

  const getSessions = (data) => {
    console.log(data, reid);
    let isError = validateForm(data);
    if (isError.status) {
      apiRequest(
        props.sessionToken,
        "get_session",
        data,
        (res) => {
          if (res.status === 200) {
            console.log(res.data);
            setRowData(res.data.sessions);
            makeGrid(res.data);
          }
        },
        (err) => {
          errorHandler(err);
        }
      );
    } else {
      toaster.notify(isError.msg, {
        duration: 1500,
      });
    }
  };

  const handleDelete = (data) => {
    console.log("DEL", data);
  };

  const handleReset = (data) => {
    console.log("RESET", data);
  };

  const makeGrid = (data) => {
    let cols = [];
    data.sessions.map((ele) => {
      Object.keys(ele).map((key) => cols.push(key));
    });
    let localCols = [];
    if (isResourcePresent(props.resources, "del_session")) {
      localCols.push({
        headerName: "Delete Sessio",
        cellRenderer: "buttonRenderer",
        cellRendererParams: {
          onClick: handleDelete,
          label: "Delete",
        },
      });
    }
    if (isResourcePresent(props.resources, "reset_session")) {
      localCols.push({
        headerName: "Reset Session",
        cellRenderer: "dropDownRenderer",
        cellRendererParams: {
          onClick: handleReset,
          label: "RESET",
          dropDown: resetSessionOptions,
        },
      });
    }
    cols = [...new Set(cols)];
    colsToExlude.map((key) => {
      let ind = cols.indexOf(key);
      if (ind > -1) {
        cols.splice(ind, 1);
      }
    });
    let finalColDefs = [...localCols, ...columnDefsFromArr(cols)];
    setColumnDefs(finalColDefs);
  };

  const validateForm = (data) => {
    if (data.reid.trim() === "") {
      return { status: false, msg: "Email/Email Id is reqd" };
    } else {
      return { status: true };
    }
  };

  return (
    <div className="container-fluid">
      <div>
        <h5>Get Sessions Information</h5>
      </div>

      <div className="card mt-2 p-3 bg-red shadow p-3 mb-5 bg-white rounded">
        <div className="row m-2">
          <div className="col-sm-6">
            <input
              type="text"
              className="form-control"
              value={email || ""}
              placeholder="Email / Email ID"
              onChange={handleEmailChange}
            />
          </div>
          <div className="col-sm-2">
            <button className="button btn-primary" onClick={handleGetSession}>
              Get Information
            </button>
          </div>
        </div>
      </div>
      {rowData == null ? null : (
        <div className="card mt-2 p-3 bg-red shadow p-3 mb-5 bg-white rounded">
          <div
            className="ag-theme-balham"
            style={{ height: "500px", width: "100%" }}
          >
            <AgGridReact
              defaultColDef={defaultColDef}
              columnDefs={columnDefs}
              rowData={rowData}
              frameworkComponents={frameworkComponents}
            ></AgGridReact>
          </div>
        </div>
      )}
    </div>
  );
}

export { Sessions };

ButtonRenderer.js按钮渲染器.js

import React from "react";

function ButtonRenderer(params) {
  const refresh = (param) => {
    return true;
  };

  const onClick = ($event) => {
    if (params.onClick instanceof Function) {
      const retParams = {
        event: $event,
        rowData: params.node.data,
      };
      params.onClick(retParams);
    }
  };
  return (
    <button className="button btn-primary" onClick={onClick}>
      {params.label}
    </button>
  );
}

export { ButtonRenderer };

DropDownRenderer.js DropDownRenderer.js

import React, { useState } from "react";

function DropDownRender(params) {
  const [selection, setSelection] = useState(params.dropDown[0]);
  const refresh = (param) => {
    return true;
  };

  const handleDropDown = (e) => {
    setSelection(e.target.value);
  };

  const onClick = ($event) => {
    if (params.onClick instanceof Function) {
      const retParams = {
        event: $event,
        rowData: params.node.data,
        selection: selection,
      };
      params.onClick(retParams);
    }
  };
  return (
    <div className="row">
      <div className="col">
        <select className="form-control" onChange={handleDropDown}>
          {params.dropDown.map((i) => {
            return (
              <option key={i} value={i}>
                {i}
              </option>
            );
          })}
        </select>
      </div>
      <div className="col">
        <button className="button btn-primary" onClick={onClick}>
          {params.label}
        </button>
      </div>
    </div>
  );
}

export { DropDownRender };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 navigationOptions 添加到记忆化的反应功能组件? - How to add navigationOptions to a memoized react functional component? 单击按钮时,如何添加选定的 class 并从 React 功能组件中的所有其他按钮中删除? - On button click, how to add selected class and remove from all other buttons in React functional component? 如何在单击一次按钮时呈现另一个反应组件? (功能组件) - How to render another react component on a single button click? (Functional Component) 如何处理 React JS 中的组单选按钮 - 功能组件 - How to handle group radio button in React JS - FUNCTIONAL COMPONENT 如何在反应功能组件中为按钮变量切换 className? - How do I toggle className for button variable in react functional component? 如何在 React 功能组件中添加删除线或修改 css - How to Add a line strikethrough or modify css in React Functional Component 如何在 React 功能组件中添加 Redux function 作为带有 Props 的参数 - How to Add Redux function as a Parameter with Props in React Functional Component 如何更新/添加新数据以响应功能组件对象? - How to update/add new data to react functional component object? 如何在 React 功能组件中使用 Props 添加 Redux object 作为参数 - How to Add Redux object as a Parameter with Props in React Functional Component 单击按钮时调用功能组件反应 - Call functional Component on button click in react
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM