对于 JS 来说,React 还算陌生。尝试将 Material 表与添加行按钮一起使用。 添加行不会添加行。一刷新行就被重置。 我很确定我在设置/更新状态时做错了什么。
export default function App() {
return (
<div className="App">
<Tabl
obj={{
a: "a",
items: [{ x: 1 }, { x: 2 }, { x: 3 }]
}}
/>
</div>
);
}
class Tabl extends Component {
constructor(props) {
super(props);
this.state = {
obj: props.obj
};
console.log(JSON.stringify(this.state.obj));
}
updateState(newData) {
this.setState({
obj: [...this.state.obj.items, newData]
});
}
render() {
const currObj = this.state.obj;
const column = [
{
title: "a",
field: "x"
}
];
const tableIcons = {
Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />)
};
return (
<MaterialTable
data={currObj.items}
columns={column}
icons={tableIcons}
options={{
search: false,
paging: false
}}
editable={{
onRowAdd: (newData) =>
new Promise((resolve, reject) => {
setTimeout(() => {
this.updateState(newData);
resolve();
}, 1000);
})
}}
/>
);
}
}
export default Tabl;
提前致谢。
最佳答案
this.updateState 方法未绑定(bind)到类。
您可以像这样在构造函数中绑定(bind),
constructor(props) {
super(props);
this.state = {
obj: props.obj
};
console.log(JSON.stringify(this.state.obj));
this.updateState= this.updateState.bind(this);
}
关于javascript - Material 表不会添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64817680/