将动态生成的复选框添加到react-table并捕获行数据

时间:2017-10-03 19:14:43

标签: javascript reactjs

我在使用此react-table软件包https://react-table.js.org/#/story/readme

向行添加复选框时遇到问题

我试图在表格的每一行添加一个复选框。我尝试添加"复选框"到了" Cell"然而,在列区域中看到的价值似乎并不适用于分页。一旦我点击下一页然后退回它就会忘记所有以前检查过的产品。我如何保持他们的状态?

我添加了一个键,它可以防止在所有页面上检查该元素,但是,当我在页面上来回切换时,它不会记住它。所以我只需将其存储在状态"现在。

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

这里是完整的代码:

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"
          />
  );}
}

2 个答案:

答案 0 :(得分:2)

我最终在点击时将标题存储到哈希中,这给了我最终的解决方案。它检查散列状态以查看该值是否为true并应保持检查状态。见下面的代码。希望它能帮到别人!另请查看我曾经帮助过的codepen示例。

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"
          />
  );}
}

答案 1 :(得分:0)

要解决检查所有页面中的项目的问题,只需在key组件上添加<Checkbox />道具。

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