[英]React-Table Column Hiding
I'm kind of new to React and Web development in general.一般来说,我对 React 和 Web 开发有点陌生。
I have a scenario, to create a table in react, and create a box that would enable to show/hide the columns with it, and along with it a select all checkbox that would show or hide all columns except a "NAME_ID" column.我有一个场景,要在反应中创建一个表,并创建一个可以显示/隐藏列的框,以及一个select all 复选框,它将显示或隐藏除“NAME_ID”列之外的所有列。 I am able to achieve the earlier part with with
useTable()
hook and column.getToggleHiddenProps()
method from destructured call of hook.我可以使用
useTable()
钩子和column.getToggleHiddenProps()
方法从钩子的解构调用中实现前面的部分。
But I'm not able to achieve the second part, I do know that we have getToggleHideAllColumnsProps()
but that won't allow me to except the required NAME_ID column.但我无法实现第二部分,我知道我们有
getToggleHideAllColumnsProps()
但这不允许我除了所需的NAME_ID列。
Any help or suggestions would be great.!.任何帮助或建议都会很棒。!
There is a way to accomplish this.有一种方法可以做到这一点。 I wish this was a boolean to pass to the Columns object, but we take what we can get.
我希望这是一个 boolean 传递给列 object,但我们采取我们能得到的。
I forked the original Hidden Columns sandbox as a proof of concept. 我分叉了原始的 Hidden Columns 沙箱作为概念证明。 The relevant portions are:
相关部分是:
getToggleHideAllColumnsProps
props, you need to create your own onClick handler.getToggleHideAllColumnsProps
道具。 column
exposes a toggleHidden
method which dictates the behavior when the user attempts to toggle that specific column. column
公开了一个toggleHidden
方法,该方法指示用户尝试切换该特定列时的行为。 Somewhat frustratingly, even if you have implemented the toggleHidden
method for a column, getToggleHideAllColumnsProps
completely ignores it, and toggles its hidden status anyway.toggleHidden
方法, getToggleHideAllColumnsProps
完全忽略它,并且无论如何都会切换它的隐藏状态。<div>
<IndeterminateCheckbox
onClick={() => allColumns.forEach(c => c.id !== "firstName" && c.toggleHidden())}
/>
Toggle All
</div>
Luckily, it is a fairly simple function -- just iterate over your columns
object and call toggleHidden
on each.幸运的是,它是一个相当简单的 function - 只需遍历您的
columns
object 并在每个列上调用toggleHidden
。 I included a check against calling it on the desired column anyway, for robustness, but you technically don't need to.无论如何,为了稳健性,我在所需的列上包含了一个反对调用它的检查,但从技术上讲,你不需要这样做。
toggleHidden
function for the desired column.toggleHidden
function。 I did it in the render method for the checkboxes, but it works just the same if you do it elsewhere.toggleHidden
function is defined for a column, it overrides the default behavior, as expected.toggleHidden
function 时,它会覆盖默认行为,如预期的那样。 So, you can just have an empty function that returns null, and this disables the ability to manually turn off that column.allColumns.map((column) => {
if (column.id === "firstName") {
column.toggleHidden = () => null;
}
return ( /* ...jsx... */ );
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.