如何在Material UI DataGrid中删除特定行(Reactjs)

huangapple go评论89阅读模式
英文:

How to delete a specific row in Material UI DataGrid (Reactjs)

问题

import React, { Component } from 'react';
import { DataGrid } from '@material-ui/data-grid';
import Button from '@material-ui/core/Button';

const columns = [
  { field: 'id', headerName: 'ID', width: 70 },
  { field: 'firstName', headerName: 'First name', width: 130 },
  { field: 'lastName', headerName: 'Last name', width: 130 },
  {
    field: 'age',
    headerName: 'Age',
    type: 'number',
    width: 90,
  },
  {
    field: 'fullName',
    headerName: 'Full name',
    description: 'This column has a value getter and is not sortable.',
    sortable: false,
    width: 160,
    valueGetter: (params) =>
      `${params.getValue('firstName') || ''} ${params.getValue('lastName') || ''}`,
  },
  { field: 'city', headerName: 'City', width: 100 },
  { field: 'state', headerName: 'State', width: 100 },
];

const rows = [
  // ... (sample JSON data)
];

class ElgibleContracts extends Component {
  getInfo = () => {
    // Logic to handle row deletion and tracking
  };

  render() {
    return (
      <div style={{ textAlign: 'center' }}>
        <h1 style={{ fontFamily: 'Stone' }}>Elgible Contracts</h1>
        <span className="horizontal-line" />
        <div className="centerDiv" style={{ height: 380, width: 950 }}>
          <DataGrid rows={rows} columns={columns} pageSize={10} checkboxSelection />
        </div>
        <br />
        <Button variant="contained" color="primary" onClick={this.getInfo}>
          Purge
        </Button>
      </div>
    );
  }
}

export default ElgibleContracts;

Note: The code provided doesn't include the logic for handling row deletion and tracking, as it seems that this is the part you're struggling with. You would need to implement the getInfo method inside the ElgibleContracts component to achieve the desired functionality.

英文:

I'm starting this project in react & currently it's going well.
However, I'm having an issue.

My desired functionality is this: I desire to delete every row that you see where the checkbox for that row is clicked. For example, if I click the checkbox in rows 1 & 3, I want rows 1 & 3 to be deleted. I also want to keep track of the rows that I decide to delete.

The issue is that I have no idea how to do that, and even after doing research I still feel stuck on how to approach this problem.

Currently I'm populating this table with some sample JSON data I found online, so don't mind the weird data that's present. Also, if anybody has recommendations for an easier or cleaner way to achieve this, then feel free to let me know about it in the comments.

Here's the code:

import React, { Component } from &#39;react&#39;;
import { DataGrid } from &#39;@material-ui/data-grid&#39;;
import Button from &#39;@material-ui/core/Button&#39;;
const columns = [
{ field: &#39;id&#39;, headerName: &#39;ID&#39;, width: 70 },
{ field: &#39;firstName&#39;, headerName: &#39;First name&#39;, width: 130 },
{ field: &#39;lastName&#39;, headerName: &#39;Last name&#39;, width: 130 },
{
field: &#39;age&#39;,
headerName: &#39;Age&#39;,
type: &#39;number&#39;,
width: 90,
},
{
field: &#39;fullName&#39;,
headerName: &#39;Full name&#39;,
description: &#39;This column has a value getter and is not sortable.&#39;,
sortable: false,
width: 160,
valueGetter: (params) =&gt;
`${params.getValue(&#39;firstName&#39;) || &#39;&#39;} ${params.getValue(&#39;lastName&#39;) || &#39;&#39;}`,
},
{ field: &#39;city&#39;, headerName: &#39;City&#39;, width: 100 },
{ field: &#39;state&#39;, headerName: &#39;State&#39;, width: 100 },
];
const rows = [
{ id: 1, lastName: &#39;Snow&#39;, firstName: &#39;Jon&#39;, age: 35, city: &#39;Milwaukee&#39;, state: &#39;Wisconsin&#39; },
{ id: 2, lastName: &#39;Lannister&#39;, firstName: &#39;Cersei&#39;, age: 42, city: &#39;Dubuque&#39;, state: &#39;Iowa&#39; },
{ id: 3, lastName: &#39;Lannister&#39;, firstName: &#39;Jaime&#39;, age: 45, city: &#39;Appleton&#39;, state: &#39;Wisconsin&#39;},
{ id: 4, lastName: &#39;Stark&#39;, firstName: &#39;Arya&#39;, age: 16, city: &#39;Madison&#39;, state: &#39;Wisconsin&#39; },
{ id: 5, lastName: &#39;Targaryenmnsdlfbsjbgjksbgksbfksfgbk&#39;, firstName: &#39;Daenerys&#39;, age: null, city: &#39;Green Bay&#39;, state: &#39;Wisconsin&#39; },
{ id: 6, lastName: &#39;Melisandre&#39;, firstName: null, age: 150, city: &#39;San Antonio&#39;, state: &#39;Texas&#39; }, 
{ id: 7, lastName: &#39;Clifford&#39;, firstName: &#39;Ferrara&#39;, age: 44, city: &#39;Dallas&#39;, state: &#39;Texas&#39; },
{ id: 8, lastName: &#39;Frances&#39;, firstName: &#39;Rossini&#39;, age: 36, city: &#39;Brooklyn&#39;, state: &#39;New York&#39; },
{ id: 9, lastName: &#39;Roxie&#39;, firstName: &#39;Harvey&#39;, age: 65, city: &#39;Toledo&#39;, state: &#39;Ohio&#39; },
{ id: 10, lastName: &#39;Larry&#39;, firstName: &#39;King&#39;, age: 105, city: &#39;Chicago&#39;, state: &#39;Illiniois&#39; },
{ id: 11, lastName: &#39;Snow&#39;, firstName: &#39;Jon&#39;, age: 35, city: &#39;Milwaukee&#39;, state: &#39;Wisconsin&#39; },
{ id: 12, lastName: &#39;Lannister&#39;, firstName: &#39;Cersei&#39;, age: 42, city: &#39;Dubuque&#39;, state: &#39;Iowa&#39; },
{ id: 13, lastName: &#39;Lannister&#39;, firstName: &#39;Jaime&#39;, age: 45, city: &#39;Appleton&#39;, state: &#39;Wisconsin&#39;},
{ id: 14, lastName: &#39;Stark&#39;, firstName: &#39;Arya&#39;, age: 16, city: &#39;Madison&#39;, state: &#39;Wisconsin&#39; },
{ id: 15, lastName: &#39;Targaryenmnsdlfbsjbgjksbgksbfksfgbk&#39;, firstName: &#39;Daenerys&#39;, age: null, city: &#39;Green Bay&#39;, state: &#39;Wisconsin&#39; },
{ id: 16, lastName: &#39;Melisandre&#39;, firstName: null, age: 150, city: &#39;San Antonio&#39;, state: &#39;Texas&#39; }, 
{ id: 17, lastName: &#39;Clifford&#39;, firstName: &#39;Ferrara&#39;, age: 44, city: &#39;Dallas&#39;, state: &#39;Texas&#39; },
{ id: 18, lastName: &#39;Frances&#39;, firstName: &#39;Rossini&#39;, age: 36, city: &#39;Brooklyn&#39;, state: &#39;New York&#39; },
{ id: 19, lastName: &#39;Roxie&#39;, firstName: &#39;Harvey&#39;, age: 65, city: &#39;Toledo&#39;, state: &#39;Ohio&#39; },
{ id: 20, lastName: &#39;Larry&#39;, firstName: &#39;King&#39;, age: 105, city: &#39;Chicago&#39;, state: &#39;Illiniois&#39; },
];
class ElgibleContracts extends Component {
render(){
return (
&lt;div style={{textAlign: &quot;center&quot;}}&gt;
&lt;h1 style={{fontFamily: &quot;Stone&quot;}}&gt;Elgible Contracts&lt;/h1&gt;
&lt;span className=&quot;horizontal-line&quot; /&gt;
&lt;div className=&quot;centerDiv&quot; style={{ height: 380, width: 950}}&gt;
&lt;DataGrid rows={rows} columns={columns} pageSize={10} checkboxSelection /&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;Button variant=&quot;contained&quot; color=&quot;primary&quot; onClick={this.getInfo} &gt;Purge&lt;/Button&gt;
&lt;/div&gt;
)
}
}
export default ElgibleContracts;

如何在Material UI DataGrid中删除特定行(Reactjs)

答案1

得分: 3

我为此创建了一个沙盒https://codesandbox.io/s/heuristic-davinci-n3vrz?file=/src/App.js

我使用了函数组件和钩子因为这是现今的最佳实践

const [rows, setRows] = useState(data);
const [deletedRows, setDeletedRows] = useState([]);

const handleRowSelection = (e) => {
  setDeletedRows([...deletedRows, ...rows.filter((r) => r.id === e.data.id)]);
};

const handlePurge = () => {
  setRows(
    rows.filter((r) => deletedRows.filter((sr) => sr.id === r.id).length < 1)
  );
};

return (
  <div style={{ textAlign: "center" }}>
    <h1 style={{ fontFamily: "Stone" }}>Eligible Contracts</h1>
    <span className="horizontal-line" />
    <div className="centerDiv" style={{ height: 380, width: 950 }}>
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={10}
        checkboxSelection
        onRowSelected={handleRowSelection}
      />
    </div>
    <br />
    <Button variant="contained" color="primary" onClick={handlePurge}>
      Purge
    </Button>
  </div>
);
英文:

I created a sandbox for this: https://codesandbox.io/s/heuristic-davinci-n3vrz?file=/src/App.js

I used functional components and hooks since this is best practice nowadays.

   const [rows, setRows] = useState(data);
const [deletedRows, setDeletedRows] = useState([]);
const handleRowSelection = (e) =&gt; {
setDeletedRows([...deletedRows, ...rows.filter((r) =&gt; r.id === e.data.id)]);
};
const handlePurge = () =&gt; {
setRows(
rows.filter((r) =&gt; deletedRows.filter((sr) =&gt; sr.id === r.id).length &lt; 1)
);
};
return (
&lt;div style={{ textAlign: &quot;center&quot; }}&gt;
&lt;h1 style={{ fontFamily: &quot;Stone&quot; }}&gt;Elgible Contracts&lt;/h1&gt;
&lt;span className=&quot;horizontal-line&quot; /&gt;
&lt;div className=&quot;centerDiv&quot; style={{ height: 380, width: 950 }}&gt;
&lt;DataGrid
rows={rows}
columns={columns}
pageSize={10}
checkboxSelection
onRowSelected={handleRowSelection}
/&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;Button variant=&quot;contained&quot; color=&quot;primary&quot; onClick={handlePurge}&gt;
Purge
&lt;/Button&gt;

答案2

得分: 1

const ElgibleContracts = () => {
  const [items, setItems] = React.useState(rows);
  const [selection, setSelection] = React.useState([]);
  const [deleted, setDeleted] = React.useState([]);
  
  const handlePurge = () => {
    setDeleted([...deleted, ...selection]);
    setItems(items.filter(i => !selection.some(s => s.id === i.id)));
    setSelection([]);
  };
  
  console.log("Here are deleted items", deleted);
  
  return (
    <div style={{ textAlign: "center" }}>
      <h1 style={{ fontFamily: "Stone" }}>Eligible Contracts</h1>
      <span className="horizontal-line" />
      <div className="centerDiv" style={{ height: 380, width: 950 }}>
        <DataGrid
          onSelectionChange={(newSelection) => {
            setSelection(newSelection.rows);
          }}
          rows={items}
          columns={columns}
          pageSize={10}
          checkboxSelection
        />
      </div>
      <br />
      <Button variant="contained" color="primary" onClick={handlePurge}>Purge</Button>
    </div>
  );
};
英文:
const ElgibleContracts = () =&gt; {
const [items, setItems] = React.useState(rows)
const [selection, setSelection] = React.useState([]);
const [deleted, setDeleted] = React.useState([])
const handlePurge = () =&gt; {
setDeleted([...deleted, ...selection])
setItems(items.filter(i=&gt; !selection.some(s=&gt; s.id === i.id)))
setSelection([])
}
console.log(&quot;Here are deleted items&quot;,deleted)
return (
&lt;div style={{textAlign: &quot;center&quot;}}&gt;
&lt;h1 style={{fontFamily: &quot;Stone&quot;}}&gt;Elgible Contracts&lt;/h1&gt;
&lt;span className=&quot;horizontal-line&quot; /&gt;
&lt;div className=&quot;centerDiv&quot; style={{ height: 380, width: 950}}&gt;
&lt;DataGrid  onSelectionChange={(newSelection) =&gt; {
setSelection(newSelection.rows);
}} rows={items} columns={columns} pageSize={10} checkboxSelection /&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;Button variant=&quot;contained&quot; color=&quot;primary&quot; onClick={handlePurge} &gt;Purge&lt;/Button&gt;
&lt;/div&gt;
)
}

答案3

得分: 0

onRowSelected的使用可能会很快出现错误,因为当在DataGrid中取消选择项目时,您必须重置deletedRows。这就是为什么我建议使用onSelectionModelChange

const [rows, setRows] = useState(data);
const [deletedRows, setDeletedRows] = useState([]);

<DataGrid
  checkboxSelection
  columns={columns}
  pageSize={5}
  onSelectionModelChange={({selectionModel}) => {
    const rowIds = selectionModel.map(rowId => parseInt(String(rowId), 10));
    const rowsToDelete = rows.filter(row => rowIds.includes(row.id));
    setDeletedRows(rowsToDelete);
  }}
  rows={rows}
/>
英文:

The usage of onRowSelected can end up in errors quickly because you have to reset the deletedRows when unselecting items in the DataGrid. That's why I suggest to make use of onSelectionModelChange:

const [rows, setRows] = useState(data);
const [deletedRows, setDeletedRows] = useState([]);

&lt;DataGrid
  checkboxSelection
  columns={columns}
  pageSize={5}
  onSelectionModelChange={({selectionModel}) =&gt; {
    const rowIds = selectionModel.map(rowId =&gt; parseInt(String(rowId), 10));
    const rowsToDelete = rows.filter(row =&gt; rowIds.includes(row.id));
    setDeletedRows(rowsToDelete);
  }}
  rows={rows}
/&gt;

huangapple
  • 本文由 发表于 2020年10月7日 03:52:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64232909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定