javascript 将动态生成的复选框添加到反应表并捕获行数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46551810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:46:07  来源:igfitidea点击:

Adding dynamically generated checkboxes to react-table and capturing row data

javascriptreactjs

提问by ByteMe

I'm having trouble adding checkboxes to rows using this react-table package https://react-table.js.org/#/story/readme

我在使用这个 react-table 包https://react-table.js.org/#/story/readme向行添加复选框时遇到问题

I'm trying to add a checkbox to each row in my table. I tried adding "checkbox" to the "Cell" value seen in the columns area, however, it seems that it doesn't work well with the pagination. Once I click next page and then back it forgets all of the previously checked products. How do I maintain their state?

我正在尝试为表中的每一行添加一个复选框。我尝试将“复选框”添加到列区域中看到的“单元格”值中,但是,它似乎不适用于分页。一旦我点击下一页然后返回它就会忘记所有以前检查过的产品。我如何保持他们的状态?

I added a key, and it prevents the element from being checked on all pages, however, it doesn't remember it when I change back and forth on the pages. So I just need to store its "on state" now.

我添加了一个键,它阻止在所有页面上检查元素,但是,当我在页面上来回更改时,它不记得它。所以我现在只需要存储它的“开启状态”。

Cell: rowInfo => (<Checkbox key={rowInfo.index} onChange={this.handleChange} />)

Here's the full code:

这是完整的代码:

import React from 'react'
import ReactDOM from 'react-dom'
import ReactTable from 'react-table'
import PropTypes from 'prop-types'
import { Checkbox } from '@shopify/polaris';

export default class ProductIndexTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
     rowInfo: '' 
    }
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange(event) {
  }
  render() {
    function CreateItem(product) {
      return { 
        title: <a href={'/products/' + product.id} >{product.title}</a>,
        price_test_status: product.has_active_price_test,
        price_test_completion_percentage: product.price_test_completion_percentage
      }
    }
  return (<ReactTable
            data={this.props.products.map(CreateItem)}
            getTdProps={(state, rowInfo, column, instance) => {
              return {
                onClick: (e, handleOriginal) => {
                  // console.log('A Td Element was clicked!')
                  // console.log('it produced this event:', e)
                  // console.log('It was in this column:', column)
                  // console.log('It was in this row:', rowInfo)
                  // console.log('It was in this table instance:', instance)
                  this.setState({
                    rowInfo: rowInfo.index
                  })
                  // IMPORTANT! React-Table uses onClick internally to trigger
                  // events like expanding SubComponents and pivots.
                  // By default a custom 'onClick' handler will override this functionality.
                  // If you want to fire the original onClick handler, call the
                  // 'handleOriginal' function.
                  if (handleOriginal) {
                    handleOriginal()
                  }
                }
              }
            }}
            columns={[
            {
              Header: "Base",
              columns: [
                {
                  Header: <Checkbox />,
                  maxWidth: 50,
                  Cell: (<Checkbox onChange={this.handleChange} />)
                }, {
                  Header: "Product Title",
                  accessor: "title",
                  maxWidth: 400
                }, {
                  Header: "Price Test Status",
                  accessor: "price_test_status",
                  maxWidth: 200
                }, {
                  Header: "Price Test Completion Percentage",
                  accessor: "price_test_completion_percentage",
                  Cell: row => (
                    <div
                      style={{
                        width: '100%',
                        height: '100%',
                        backgroundColor: '#dadada',
                        borderRadius: '2px'
                      }}
                    >
                    <div
                      style={{
                        width: `${row.value}%`,
                        height: '100%',
                        backgroundColor: row.value > 66 ? '#85cc00'
                          : row.value > 33 ? '#ffbf00'
                          : '#ff2e00',
                        borderRadius: '2px',
                        transition: 'all .2s ease-out'
                      }}
                    />
                    </div>
                  )
                }
              ]
            }
            ]}
            defaultPageSize={10}
            className="-striped -highlight"
          />
  );}
}

回答by ByteMe

I ended up storing the titles into a hash when clicked and that gave me my final solution. It checks the hash state to see if the value is true and should remain checked. See code below. Hope it helps others! Also check the codepen example I used to help me.

我最终在单击时将标题存储到哈希中,这给了我最终的解决方案。它检查散列状态以查看该值是否为真并应保持检查状态。请参阅下面的代码。希望它能帮助别人!还要检查我用来帮助我的 codepen 示例。

https://codepen.io/aaronschwartz/pen/WOOPRw?editors=0010

https://codepen.io/aaronschwartz/pen/WOOPRw?editors=0010

import React from 'react'
import ReactDOM from 'react-dom'
import ReactTable from 'react-table'
import PropTypes from 'prop-types'
import { Checkbox } from '@shopify/polaris';

export default class ProductIndexTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
     selected: {},
     selectAll: 0,
     products: this.props.products
    }
    this.toggleRow = this.toggleRow.bind(this);
  }
    toggleRow(title) {
        const newSelected = Object.assign({}, this.state.selected);
        newSelected[title] = !this.state.selected[title];
        this.setState({
            selected: newSelected,
            selectAll: 2
        });
    }
    toggleSelectAll() {
        let newSelected = {};
        if (this.state.selectAll === 0) {
            this.state.products.forEach(x => {
                newSelected[x.title] = true;
            });
        }
        this.setState({
            selected: newSelected,
            selectAll: this.state.selectAll === 0 ? 1 : 0
        });
    }

  render() {
    function CreateItem(product) {
      return { 
        title: <a href={'/products/' + product.id} >{product.title}</a>,
        price_test_status: product.has_active_price_test,
        price_test_completion_percentage: product.price_test_completion_percentage
      }
    }
  return (<ReactTable
            data={this.props.products.map(CreateItem)}
            columns={[
            {
              Header: "Base",
              columns: [
                {
                            id: "checkbox",
                            accessor: "",
                            Cell: ( rowInfo ) => {
                                return (
                                    <Checkbox
                                        type="checkbox"
                                        className="checkbox"
                                      checked={this.state.selected[rowInfo.original.title.props.children] === true}
                                        onChange={() => this.toggleRow(rowInfo.original.title.props.children)}
                                    />
                                );
                            },
                            Header: title => {
                                return (
                                    <Checkbox
                                        type="checkbox"
                                        className="checkbox"
                                        checked={this.state.selectAll === 1}
                                        ref={input => {
                                            if (input) {
                                                input.indeterminate = this.state.selectAll === 2;
                                            }
                                        }}
                                        onChange={() => this.toggleSelectAll()}
                                    />
                                );
                            },
                            sortable: false,
                            width: 45
                        },                
                {
                  Header: "Product Title",
                  accessor: "title",
                  maxWidth: 400
                }, {
                  Header: "Price Test Status",
                  accessor: "price_test_status",
                  maxWidth: 200
                }, {
                  Header: "Price Test Completion Percentage",
                  accessor: "price_test_completion_percentage",
                  Cell: row => (
                    <div
                      style={{
                        width: '100%',
                        height: '100%',
                        backgroundColor: '#dadada',
                        borderRadius: '2px'
                      }}
                    >
                    <div
                      style={{
                        width: `${row.value}%`,
                        height: '100%',
                        backgroundColor: row.value > 66 ? '#85cc00'
                          : row.value > 33 ? '#ffbf00'
                          : '#ff2e00',
                        borderRadius: '2px',
                        transition: 'all .2s ease-out'
                      }}
                    />
                    </div>
                  )
                }
              ]
            }
            ]}
            defaultPageSize={10}
            className="-striped -highlight"
          />
  );}
}

回答by Carlos A. Jimenez Holmquist

To solve the problem of checking the items in all the pages, just add the keyprop on the <Checkbox />components.

解决所有页面的item都勾选的问题,只需要key<Checkbox />组件上加上prop即可。

Now, with the problem of storing the state, how many checkboxes are we talking about? You should have an array in your state, with all the checkboxes, and once a checkbox is checked you could send the ID (keyprops, which could be the counter on the .map()) and set that position of the array as true or false (checked or unchecked)

现在,关于存储状态的问题,我们谈论的是多少个复选框?您的状态中应该有一个包含所有复选框的数组,一旦选中一个复选框,您就可以发送 ID(key道具,可能是 上的计数器.map())并将数组的该位置设置为 true 或 false(选中或未选中)