简体   繁体   English

如何在本机表组件中选中/取消选中单个复选框

[英]How to check/uncheck individual checkbox in react-native Table component

I am working on sample application. 我正在研究示例应用程序。 In that I used the table component to push the row, col values into an empty array. 在这种情况下,我使用表组件将行,col值压入一个空数组。 If the row, col values exist in empty array it has to show the check mark and if user clicks(or) selects the checked one again it has to uncheck. 如果该行的col值存在于空数组中,则必须显示复选标记,并且如果用户单击(或)再次选择已选中的值,则必须取消选中该值。 Can anyone please suggest me how to resolve this issue? 谁能建议我如何解决此问题? Any best solutions are appreciated. 任何最好的解决方案表示赞赏。

_showData = (data,i,j) => {

  this.setState({iValue:i,jValue:j},()=>{
    //this.fetchData()
        this.state.tableCellData.push({"i":i,"j":j})
        this.setState({isSelected:true,tableCellData:this.state.tableCellData},()=>{/*alert("array:"+JSON.stringify(this.state.tableCellData))*/})

        if(this.state.isSelected == true){
          this.setState({isSelected:false})
        }else{
          this.setState({isSelected:true})
        }

    this.state.tableCellData.map((item, index) => {
     if(item.i == i && item.j == j){
       this.state.tableCellData.splice(index,0)
       this.setState({isSelected:false})
       alert("splice:"+JSON.stringify(this.state.tableCellData))
     }
   })
  this.fetchData()

  })

}

I used this _showdata function to show clickable action on each cell data 我使用了此_showdata函数来显示每个单元格数据上的可点击操作

请检查上面显示表格视图的图像

Try to avoid mutating the state. 尽量避免改变状态。 This is how you can add an item to the state without mutating it: 这样可以将项目添加到状态而无需对其进行更改:

this.setState({
    isSelected:true,
    tableCellData: [
        ...this.state.tableCellData, 
        {i, j}
    ]
});

Notice that I didn't push the new data directly to the tableCellData array (which would be a state mutation), but instead I created a new tableCellData array. 请注意,我没有将新数据直接推送到tableCellData数组(这将是状态突变),而是创建了一个新的tableCellData数组。 I then updated the state using the new array. 然后,我使用新数组更新了状态。 There's a good reason for this. 这是有充分的理由的。

If you mutate the state (like in the code you posted), then oldState.tableCellData === newState.tableCellData (they both point to the same object in memory). 如果oldState.tableCellData === newState.tableCellData状态(如发布的代码一样),则oldState.tableCellData === newState.tableCellData (它们都指向内存中的同一对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM