如何使用无线电输入而不是React中可选择的复选框?
有一个例子用于复选框,但不是单选按钮:https://github.com/tannerlinsley/react-table/blob/master/examples/row-selection/src/App.js
将IndeterminateCheckox更改为使用无线电输入不起作用,因为React表中没有更新选择状态:
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} />
);
});
它看起来是正确的,但没有传递正确的选择状态:
发布于 2020-04-04 15:35:50
看了一眼。试试这个:
的州
const [selectedRowId, setSelectedRowId] = useState(null);
autoResetSelectedRows: false,
传递给useTable
函数onClick={() => setSelectedRowId(row.id)}
我已经把工作代码整理在这里了。https://codesandbox.io/s/objective-faraday-gzf7y
备注:
selectedFlatRows
值迅速变化的小问题。我还没有完全研究这个问题,但我找到了https://github.com/tannerlinsley/react-table/issues/1740。问题是修复了,但我不完全确定。如果您对获取行数据有问题,请尝试查看下面的链接是否有助于Select row on click react-tableHow to get React Table Row Data Onclick https://codesandbox.io/s/tannerlinsleyreact-table-row-selection-hoisted-b4dvq?from-embed
发布于 2021-03-07 15:03:06
根据以前的答案,下面的解决方案有一些改进。
内部IndeterminateCheckbox组件
删除*/}添加
(
( b)取消所有单选按钮
c) row.getToggleRowSelectedProps().checked给出该行单选按钮的当前状态。因此,相应地转换这个值。i.e
如果选中了 ->,则更改为未检查的和
如果未选中 ->更改为选中了
//此selectedRowIds状态提供当前选择哪一行的信息。const{state:{ selectedRowIds }}=useTable( {.initialState:{列,数据,selectedRowIds:{ 2: true },//a)我希望我的第二行最初是自动当选的},},useRowSelect,hooks => {hooks.visibleColumns.push(列=> { id:“选择”,单元格:({ row,toggleAllRowsSelected,toggleRowSelected }) => { const currentState = row.getToggleRowSelectedProps();返回(<不确定性复选框{...currentState} onClick={() => { // b) toggleAllRowsSelected(false);// c) toggleRowSelected(row.id,!currentState.checked);}/> }},...columns );})
发布于 2021-02-03 13:07:53
如果有人还在努力解决这个问题,我找到了不同的解决方案。
对于输入类型,IndeterminateCheckbox与略有更改相同:
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} />
</>
);
}
);
然后,onClick我们取消选择所有行,并选择“单击”行。:)
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
复制相似问题