reactjs - Material-Table里面的开关打不开
问题描述
我正在尝试使用开关创建材料表,onclick 会更改组件的状态。
这是带有表格的组件,它具有父组件的状态作为道具。我将 rows 变量传递给材料表数据道具。Switch 是自定义呈现的字段。每当我单击它时,它都会触发 changeRow,它会在行变量中找到行索引,将其更改并保存到新变量中。然后调用 ChangeRows 来更改状态。问题是,开关没有改变。尽管我可以在控制台中清楚地看到新状态,但似乎什么都没有发生。
const StuffTable = ({rows, changeRows}) => {
const changeRow = (oldRow, e) => {
const changeData = {[e.target.name]: e.target.checked};
const newRow = {...oldRow, ...changeData};
console.log(oldRow, e);
const index = rows.findIndex(dtaRow => dtaRow.id === oldRow.id);
const newData = rows;
newData[index] = newRow;
console.log(newData);
changeRows(newData);
};
return (
<Container maxWidth="lg">
<Button onClick={() => { changeRow({id: 6}, { target: {name: 'borrowable', checked: true} }) }}>klikni</Button>
<MaterialTable
options={{
actionsColumnIndex: -1,
search: true,
exportButton: true,
exportDelimiter: ";"
}}
actions={[
{
icon: 'edit',
tooltip: 'Edit Study',
onClick: (event, rowData) => alert("Do you want to edit?")
}]}
columns={[
{ title: "Název", field: "title" },
{ title: "Stav", field: "status", render: (data) => <Chip label={data.status} color="primary" avatar={<Avatar src="/static/images/avatar/1.jpg" />} /> },
{ title: "Půjčovat", field: "borrowable", render: (data, id) => (<FormControlLabel control={<Switch checked={data.borrowable} onChange={(e) => changeRow(data, e)} name="borrowable" color="primary"/>} label={data.borrowable ? 'půjčovat' : 'nepůjčovat'} />) },
{ title: "Vidí všichni", field: "active", render: (data, id) => (<FormControlLabel control={<Switch checked={data.borrowable} onChange={(e) => changeRow(data, e)} name="borrowable" color="primary"/>} label={data.borrowable ? 'půjčovat' : 'nepůjčovat'} />) },
{ title: "Uskladněno", field: "location" },
]}
data={rows}
title="Moje věci"
/>
</Container>
);
};
export default StuffTable;
我尝试添加按钮,单击该按钮将状态更改为空数组,并且表格没有显示任何内容。但是当我用这个按钮触发changeRow(模型数据)时,结果是一样的——开关没有变化。
import React, {useEffect, useState} from 'react';
从“../components/stuffTable”导入 StuffTable;
let rows = [ {id:5, title: "prošívanice", 可借用: false, surname: "Baran", status: "zapůjčeno", location: "Praha" }, {id:6, title: "prošívanice 2",可借:假,姓:“Baran”,状态:“zapůjčeno”,位置:“Praha”},{id:7,标题:“prošívanice 3”,可借:假,姓:“Baran”,状态:“zapůjčeno” ,位置:“布尔诺”}];
这是父组件
const MyStuffPage = () => {
const [data, setData] = useState(rows);
return (
<div>
<StuffTable rows={data} changeRows={(data) => {setData(data); console.log("hou",data);}} />
</div>
);
};
export default MyStuffPage;
这是有此问题的 Codesandbox: https ://codesandbox.io/s/festive-gould-i1jf7
解决方案
每当您想向数据表呈现新数据或状态时,您都需要调用 onQueryChange,进行这些更改:在开始时创建一个 ref,如下所示:
const tableRef = useRef(null);
然后在材料表中使用它:
<MaterialTable
//add this
tableRef={tableRef}
options={{
actionsColumnIndex: -1,
search: true,
exportButton: true,
exportDelimiter: ";"
}}
然后在更新开始和必要的工作后在你的 changeRow 函数中添加:
tableRef.current.onQueryChange()
这将告诉表以正确的开关状态呈现新数据