gpt4 book ai didi

reactjs - 如何在 material-ui 数据网格行中添加按钮?

转载 作者:行者123 更新时间:2023-12-05 01:25:40 26 4
gpt4 key购买 nike

我想在 material-ui 数据网格的每一行中添加按钮...但是当我尝试这样做时,我看到如下输出(而不是按钮,它显示类似 [object Object] . enter image description here

下面是我的代码:

import { DataGrid } from "@mui/x-data-grid";
import React, { useState } from "react";

function App() {
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(params.id, "firstName") || ""} ${
params.getValue(params.id, "lastName") || ""
}`,
},
{
field: "click",
headerName: "Click",
type: <button />, /*this field stores the buttons*/
width: 90,
},
];
const [rows, setRows] = useState([
{
id: 1,
lastName: "Snow",
firstName: "<a>hello</a>",
age: 35,
click: <button>Hello</button>, /*given a button to first row*/
},
{ id: 2, lastName: "Lannister", firstName: "Cersei", age: 42 },
{ id: 3, lastName: "Lannister", firstName: "Jaime", age: 45 },
{ id: 4, lastName: "Stark", firstName: "Arya", age: 16 },
{ id: 5, lastName: "Targaryen", firstName: "Daenerys", age: null },
{ id: 6, lastName: "Melisandre", firstName: null, age: 150 },
{ id: 7, lastName: "Clifford", firstName: "Ferrara", age: 44 },
{ id: 8, lastName: "Frances", firstName: "Rossini", age: 36 },
{ id: 9, lastName: "Roxie", firstName: "Harvey", age: 65 },
]);
// setRows(

// setRows(rows);
// );
const [count, setCount] = useState(0);

const [arr, setArr] = useState([1, 2, 3]);
return (
<>
<p>you pressed {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
<div style={{ height: 400, width: "50%" }}>
<DataGrid
rows={rows}
columns={columns}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection
/>
</div>
<table>
{arr.map((n) => (
<tr>${n}</tr>
))}
</table>
<button
onClick={(e) => {
e.preventDefault();
arr.push(4);
console.log(arr);
var t = [...rows, { id: 3 }];
// rows.push({ lastName: "hello" });
// setRows(t);
setRows(t);
console.log(rows);
// document.title = arr;
setArr(arr);
}}
>
add
</button>
</>
);
}
export default App;

此外,插入按钮后,如何引用按钮内行的当前索引或 id,假设是否在每次单击按钮时都需要显示一个警报,其中显示 id 和 firstname 等信息那一行……我该怎么做?

最佳答案

使用渲染单元格:

{
field: "click",
headerName: "Click",
width: 90,
renderCell: (params) => {
// you will find row info in params
<button>Click</button>
}
},

关于reactjs - 如何在 material-ui 数据网格行中添加按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70737811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com