Grommet是否有一个内置的解决方案,只允许在dataTable中进行单选或多选?我想出了这个在设置数组之前清除数组的useState函数,但它有一个迫使用户单击两次的不良反应。如果array >1,则用户单击,这会将选择数组设置为[],强制用户再次单击。
import React from "react";
import ReactDOM from "react-dom";
import {Grommet, DataTable, Text, Meter, Box} from 'grommet';
const GridExample = () => {
const [select, setSelect] = React.useState([])
function handleRowSelect(selection) {
console.log(`You picked ${selection}`);
if (selection.length > 1) {
setSelect(selection[selection.length - 1].toArray)
} else {
setSelect(selection)
}
}
return (
<Grommet>
<DataTable
select={select}
onSelect={handleRowSelect}
columns={[
{
property: 'name',
search: true,
header: <Text>Name</Text>,
primary: true,
},
{
property: 'percent',
search: true,
header: 'Complete',
render: datum => (
<Box pad={{vertical: 'xsmall'}}>
<Meter
values={[{value: datum.percent}]}
thickness="small"
size="small"
/>
</Box>
),
},
]}
data={[
{name: 'Alan', percent: 20},
{name: 'Bryan', percent: 30},
{name: 'Chris', percent: 40},
{name: 'Eric', percent: 80},
]}
/>
<Text>Selected: {select}</Text>
</Grommet>
)
}
export default GridExample;
ReactDOM.render(
<GridExample/>,
document.getElementById("root")
);更新:在函数中使用Slice可以修复双击。
function handleRowSelect(selection) {
if (selection.length > 1) {
setSelect(selection.slice(-1))
} else {
setSelect(selection)
}
}发布于 2021-09-03 21:25:00
我不认为有内置的解决方案(对于grommet 2.17.5)。
不过,您始终可以尝试以不同的方式操作select和onSelect,例如,其中一种方法是向onSelect添加一个条件,并在选择了一行后禁用选择选项:
onSelect={select.length < 1 && handleRowSelect}这将确保在任何给定点只选择一行。
如果你希望用户能够重置他们的决定,你总是可以添加一个重置按钮来清除选择数组,并且复选框将被再次启用。
https://stackoverflow.com/questions/69049823
复制相似问题