检查 material-table 行是否仍处于编辑模式
Check if a material-table row is still in edit mode
我正在使用 material-table in a material-ui Stepper 并且用户倾向于点击 "next" 按钮,即使 table 仍处于编辑模式。这会导致数据丢失。
我能否以某种方式访问 table 信息以检查当用户单击 "next" 按钮时 table/row 是否仍处于编辑模式?
虽然没有直接公开的方法可以告诉你 table 是否是 editable 模式(我认为应该有),你仍然可以找到它,但是你将不得不弄乱它的内部结构。首先,您需要获取 table 的引用(find tableRef 属性),然后是 属性 对您有帮助lastEditingRow
处于table的状态。
所以,tableRef
就是:tableRef.current.state.lastEditingRow
。对于处于编辑模式的 table,lastEditingRow
将设置为描述正在编辑的行的对象,如果 table 未处于编辑模式,则 undefined
。
CodeSandbox 示例:https://codesandbox.io/s/fancy-waterfall-lg2ri
您可以使用“useRef 回调”并设置状态挂钩,例如:
// Create a state
const [isTableIsEditMode, setIsTableIsEditMode] = useState(false);
// Create a callback
const editRowRef = useCallback((editRow: React.ReactElement<any>) => setIsTableIsEditMode(!!editRow), []);
// Use the call back as a ref in your table for the Edit Row
// the ref is null if the table is not in edit mode
return <MaterialTable
components={{
...
EditRow: (props) => {
return <MTableEditRow {...props} ref={editRowRef} />;
},
}}
...
/>
我正在使用 material-table in a material-ui Stepper 并且用户倾向于点击 "next" 按钮,即使 table 仍处于编辑模式。这会导致数据丢失。
我能否以某种方式访问 table 信息以检查当用户单击 "next" 按钮时 table/row 是否仍处于编辑模式?
虽然没有直接公开的方法可以告诉你 table 是否是 editable 模式(我认为应该有),你仍然可以找到它,但是你将不得不弄乱它的内部结构。首先,您需要获取 table 的引用(find tableRef 属性),然后是 属性 对您有帮助lastEditingRow
处于table的状态。
所以,tableRef
就是:tableRef.current.state.lastEditingRow
。对于处于编辑模式的 table,lastEditingRow
将设置为描述正在编辑的行的对象,如果 table 未处于编辑模式,则 undefined
。
CodeSandbox 示例:https://codesandbox.io/s/fancy-waterfall-lg2ri
您可以使用“useRef 回调”并设置状态挂钩,例如:
// Create a state
const [isTableIsEditMode, setIsTableIsEditMode] = useState(false);
// Create a callback
const editRowRef = useCallback((editRow: React.ReactElement<any>) => setIsTableIsEditMode(!!editRow), []);
// Use the call back as a ref in your table for the Edit Row
// the ref is null if the table is not in edit mode
return <MaterialTable
components={{
...
EditRow: (props) => {
return <MTableEditRow {...props} ref={editRowRef} />;
},
}}
...
/>