问题
How can I use radio inputs instead of checkboxes for a selectable table in React Table?
There is an example for checkboxes but not radio buttons: https://github.com/tannerlinsley/react-table/blob/master/examples/row-selection/src/App.js
Changing the IndeterminateCheckox to use a radio input doesn't work as the selection state is not updated in React Table:
const IndeterminateCheckbox = React.forwardRef(({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef();
const resolvedRef = ref || defaultRef;
useEffect(() => {
resolvedRef.current.indeterminate = indeterminate;
}, [resolvedRef, indeterminate]);
return <input name="select-radio" type="radio" ref={resolvedRef} {...rest} />
);
});
It looks correct but does not pass the correct selection state back:
回答1:
Had a quick look. Try this:
- Have a state for the rowId
const [selectedRowId, setSelectedRowId] = useState(null);
- Pass
autoResetSelectedRows: false,
touseTable
function Write a click handler for the radios by hand
onClick={() => setSelectedRowId(row.id)}
I have put together the working code here. https://codesandbox.io/s/objective-faraday-gzf7y
Notes:
- There might be small issues with rapidly changing value of
selectedFlatRows
. I haven't fully researched this issue but I found https://github.com/tannerlinsley/react-table/issues/1740 . The issue says fixed but i am not completely sure. - If you have issue with grabbing row data, try and see if the below links might be helpful How to get React Table Row Data Onclick https://codesandbox.io/s/tannerlinsleyreact-table-row-selection-hoisted-b4dvq?from-embed Select row on click react-table
回答2:
In case someone is still struggling with this, I found different solution.
IndeterminateCheckbox is same with slight change for input type:
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef();
const resolvedRef = ref || defaultRef;
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate;
}, [resolvedRef, indeterminate]);
return (
<>
{/*<input type="checkbox" ref={resolvedRef} {...rest} />*/}
<input type="radio" ref={resolvedRef} {...rest} />
</>
);
}
);
Then onClick we deselect all rows, and select "clicked" row. :)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
toggleAllRowsSelected,
toggleRowSelected,
state: { selectedRowIds },
} = useTable(
{
columns,
data,
},
useRowSelect,
hooks => {
hooks.visibleColumns.push(columns => [
// Let's make a column for selection
{
id: "selection",
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => {
return (
<div>
<IndeterminateCheckbox
{...row.getToggleRowSelectedProps()}
onClick={() => {
toggleAllRowsSelected(false);
toggleRowSelected(row.id, true);
}}
/>
</div>
);
}
},
...columns
]);
}
);
来源:https://stackoverflow.com/questions/60849890/react-table-radio-input-for-userowselect