Grommet 是否有一个内置的解决方案,只允许在数据表中进行单个或多个选择?我想出了这个 useState 函数,它在设置之前清除数组,但它有强制用户单击两次的不良反应。如果数组 > 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)
}
}