【问题标题】:ReactJS - Checkbox column in react-table doesn't workReactJS - 反应表中的复选框列不起作用
【发布时间】:2020-10-07 05:32:48
【问题描述】:

我在我的项目中添加了一个可编辑的反应表 (https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/kitchen-sink),一切正常。但是,当我添加一个带有复选框的列,并勾选复选框并转到不同的页面(或排序或搜索)并返回时,勾选就消失了。这就是我将复选框添加到“列”字段的方式,

{
   Header: 'On Leave',
   accessor: 'onLeave',
   Filter: SelectColumnFilter,
   filter: 'includes',
   disableGroupBy: true,
   Cell: row => { return(
            <div style={{'text-align':'center'}}>
              <input type="checkbox" 
                value={row.value == "Yes" ? "on" : "off"} 
                onBlur={(event) => updateMyData(parseInt(row.row.id), row.column.id, event.target.checked ? "Yes" : "No")}  />
            </div>)},
}

当从复选框中失去焦点并且console.log打印正确的数据时,会触发updateMyData(),

0 : 0 : onLeave : Yes
1 : 1 : onLeave : Yes
2 : 2 : onLeave : Yes
3 : 3 : onLeave : Yes
4 : 4 : onLeave : Yes

updateMyData()如下,

// When our cell renderer calls updateMyData, we'll use
// the rowIndex, columnId and new value to update the
// original data

const updateMyData = (rowIndex, columnId, value) => {


    // We also turn on the flag to not reset the page
    skipResetRef.current = true
    setData(old =>
      old.map((row, index) => {
        if (index === rowIndex) { console.log(index + " : " +  rowIndex + " : " + columnId + " : " + value););
          return {
            ...row,
            [columnId]: value,
          }
        }
        return row
      })
    )

}

为什么复选框值没有保存在“数据”字段中?谢谢

【问题讨论】:

    标签: javascript reactjs react-table react-table-v7


    【解决方案1】:

    问题在于使用复选框“值”属性。取而代之的是,使用“defaultChecked”解决了问题,

    Cell: row => {
      return(
        <div style={{'text-align':'center'}}>
          <input type="checkbox" 
            defaultChecked={row.value == "Yes" ? true : false} 
            onBlur={(event) => updateMyData(parseInt(row.row.id), row.column.id, event.target.checked ? "Yes" : "No")}  />
        </div>)}
    

    这个问题有更多的细节, How to set default Checked in checkbox ReactJS?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2020-05-03
      相关资源
      最近更新 更多