当前位置:   article > 正文

react-table实操问题解决方法

react-table
npm install react-table

如果想要引用react-table/react-table.css,那么建议下载V6版本的react-table

简单示例代码:

  1. import React, { Component } from "react";
  2. import ReactTable from "react-table";
  3. import "react-table/react-table.css";
  4. const tableData = [
  5. { id: "1", value: "test1" },
  6. { id: "2", value: "test2" },
  7. { id: "3", value: "test3" },
  8. { id: "4", value: "test4" },
  9. { id: "5", value: "test5" },
  10. { id: "6", value: "test6" }
  11. ]
  12. class App extends Component {
  13. render() {
  14. return (
  15. <div className="boxlistcontainer">
  16. <ReactTable
  17. data={tableData}
  18. filterable
  19. defaultFilterMethod={(filter, row) =>
  20. String(row[filter.id]) === filter.value
  21. }
  22. columns={[
  23. {
  24. Header: "test",
  25. accessor: "id",
  26. sortable: false,
  27. filterable: false
  28. }
  29. ]}
  30. defaultPageSize={20}
  31. className="-striped -highlight"
  32. minRows={0}
  33. />
  34. </div>
  35. );
  36. }
  37. }
  38. export default App;

遇到的问题

解决办法,下载react-tableV6,按照下面链接这样

  1. import ReactTable from 'react-table-v6'
  2. import 'react-table-v6/react-table.css'

然后npm install react-table-v6

https://github.com/tannerlinsley/react-table/tree/v6

1.学习react-table网址

https://react-table.js.org/#/story/readme

2.分页处隐藏多余rows

将minRows = {0}加到设置页码处

  1. defaultPageSize={20}
  2. className="-striped -highlight"
  3. minRows = {0}

3.添加样式,可以将style写到对应的colums下方。同时,可以利用react-table自带的maxwidth或者width,修改默认的宽度还有其他样式变化

  1. columns={[
  2. {
  3. Header: "ID",
  4. columns: [
  5. {
  6. Header: "ID",
  7. accessor: "Id",
  8. maxWidth: 60,
  9. style:{color:'red'},

效果图

4.如果想要设置react-table的Header文本换行,只能在css文件中添加

white-space: normal;

5.如果想要设置react-table的Header文本垂直居中,只能在css文件中,为文本的父元素添加

align-items:center;display: -webkit-flex;justify-content:center;

6.如果想要对数据进行一些操作

学习文档中是这样引入数据的

  1. render() {
  2. const { data } = this.state;
  3. return (
  4. <div>
  5. <ReactTable
  6. data={data}
  7. filterable
  8. defaultFilterMethod={(filter, row) =>
  9. String(row[filter.id]) === filter.value}
  10. columns={[

我们可以这样

  1. render() {
  2. return (
  3. <div>
  4. <ReactTable
  5. data={this.props.list.map(p => {
  6. const myDate = new Date();
  7. const myTime = myDate.getTime()
  8. return {
  9. ... p,
  10. myTime
  11. };
  12. })}
  13. filterable
  14. defaultFilterMethod={(filter, row) =>
  15. String(row[filter.id]) === filter.value}
  16. columns={[

7.react-table某一列的serch和filter还有sort失效

解决,只粘贴重要代码

  1. columns: [
  2. {
  3. sortable:false,
  4. filterable:false,

8.设置打开时的默认排序或者默认筛选

  1. defaultSorted={[
  2. {
  3. id: "needReview",
  4. desc: false
  5. }
  6. ]}
  7. defaultFiltered={[
  8. {
  9. id:"needReview",
  10. value:"Yes"
  11. }
  12. ]}
  13. defaultPageSize={20}

9.当需要传入多个值时

  1. return (
  2. <div>
  3. <ReactTable
  4. data={this.props.userBoxList.map(userBox => {
  5. let boxListDiv = []
  6. let boxLen = 0
  7. }
  8. return {
  9. boxLen,
  10. boxListDiv
  11. };
  12. })}
  13. filterable
  14. defaultFilterMethod={(filter, row) =>
  15. String(row[filter.id]) === filter.value}
  16. columns={[
  1. {
  2. columns: [
  3. {
  4. Header: "",
  5. accessor: "boxListDiv",
  6. sortable: false,
  7. filterable: false,
  8. Cell: props => {
  9. return (
  10. <div>
  11. <span>{props.original.boxLen}</span><br/>
  12. <List>
  13. {props.original.boxListDiv}
  14. </List>
  15. </div>
  16. )
  17. },
  18. filterMethod: (filter, row) =>
  19. row[filter.id].startsWith(filter.value) &&
  20. row[filter.id].endsWith(filter.value)
  21. }
  22. ]
  23. },

上面只粘贴部分重要代码,虽然accessor只能够传入一个值,但是可以通过cell:props去调用前面定义的值,同时,通过在return内console.log(props)可以查看到该数据结构,从而引用数据

10.使表头固定

  1. defaultPageSize={20}
  2. style={{
  3. height: "700px" // This will force the table body to overflow and scroll, since there is not enough room
  4. }}
  5. className="-striped -highlight"
  6. minRows={0}

11.react-table Editable content 实现编辑修改内容

  1. import React, { Component } from "react";
  2. import ReactTable from "react-table";
  3. import "react-table/react-table.css";
  4. import { Icon } from "semantic-ui-react";
  5. import "semantic-ui-css/semantic.min.css";
  6. class App extends Component {
  7. constructor() {
  8. super();
  9. this.renderEditable = this.renderEditable.bind(this);
  10. this.add = this.add.bind(this);
  11. this.state={
  12. data : [
  13. { firstName: "name1" },
  14. { firstName: "name2" },
  15. { firstName: "name3" },
  16. { firstName: "name4" },
  17. { firstName: "name5" },
  18. { firstName: "name6" }
  19. ]
  20. }
  21. }
  22. handleInputChange = (cellInfo, event) => {
  23. let data = [...this.state.data];
  24. data[cellInfo.index].firstName = event.target.value;
  25. this.setState({ data });
  26. };
  27. add() {
  28. const newvalue = {
  29. // userId: this.props.item.userId,
  30. value: this.state.data
  31. };
  32. console.log('newvalue',newvalue)
  33. }
  34. renderEditable = cellInfo => {
  35. const cellIndex = cellInfo.index;
  36. const cellValue = this.state.data[cellIndex].firstName;
  37. return (
  38. <div>
  39. <input name="input" type="text"
  40. onChange={this.handleInputChange.bind(null, cellInfo)}
  41. value={cellValue} />
  42. <Icon as="i" name="add" className="edit" onClick={this.add} />
  43. </div>
  44. );
  45. };
  46. render() {
  47. return (
  48. <div>
  49. <ReactTable
  50. data={this.state.data}
  51. columns={[
  52. {
  53. Header: "First Name",
  54. accessor: "firstName",
  55. Cell: this.renderEditable
  56. }
  57. ]}
  58. defaultPageSize={10}
  59. className="-striped -highlight"
  60. >
  61. </ReactTable>
  62. </div>
  63. );
  64. }
  65. }
  66. export default App;

12.截取部分重要代码:react-table Editable content 实际应用

  1. import React, { Component } from "react";
  2. import { connect } from "react-redux";
  3. import { Icon } from "semantic-ui-react";
  4. import "semantic-ui-css/semantic.min.css";
  5. import ReactTable from "react-table";
  6. import "react-table/react-table.css";
  7. import { getTrialList } from "../action/patientAction";
  8. import {
  9. getAddTrialPatient
  10. } from "../action/addAction";
  11. class DeviceList extends Component {
  12. constructor(props) {
  13. super(props);
  14. this.state = {
  15. data: [],
  16. patientId: "",
  17. siteId: ""
  18. };
  19. this.renderEditable = this.renderEditable.bind(this);
  20. this.addPatienNo = this.addPatienNo.bind(this);
  21. }
  22. componentDidMount() {
  23. const { getTrialList } = this.props;
  24. getTrialList(this);
  25. }
  26. renderEditable = cellInfo => {
  27. let remotePatientId = cellInfo.original.patientId
  28. ? cellInfo.original.patientId
  29. : "";
  30. return (
  31. <div>
  32. <input
  33. name="input"
  34. type="text"
  35. onChange={this.handleInputChange.bind(null, cellInfo)}
  36. defaultValue={remotePatientId}
  37. />
  38. <Icon
  39. as="i"
  40. name="check"
  41. className="check"
  42. onClick={this.addPatienNo.bind(null, cellInfo)}
  43. style={{ color: "#6699CC" }}
  44. />
  45. </div>
  46. );
  47. };
  48. renderEditsiteId = cellInfo => {
  49. let remotesiteId = cellInfo.original.siteId ? cellInfo.original.siteId : "";
  50. return (
  51. <div>
  52. <input
  53. name="input"
  54. type="text"
  55. onChange={this.handleInputChange2.bind(null, cellInfo)}
  56. defaultValue={remotesiteId}
  57. />
  58. <Icon
  59. as="i"
  60. name="check"
  61. className="check"
  62. onClick={this.addPatienNo.bind(null, cellInfo)}
  63. style={{ color: "#6699CC" }}
  64. />
  65. </div>
  66. );
  67. };
  68. handleInputChange = (cellInfo, event) => {
  69. const patientId = event.target.value;
  70. this.setState({ patientId });
  71. };
  72. handleInputChange2 = (cellInfo, event) => {
  73. const siteId = event.target.value;
  74. this.setState({ siteId });
  75. };
  76. addPatienNo = cellInfo => {
  77. const { getAddTrialPatient } = this.props;
  78. const patientId =
  79. this.state.patientId === ""
  80. ? cellInfo.original.patientId
  81. : this.state.patientId;
  82. const siteId =
  83. this.state.siteId === "" ? cellInfo.original.siteId : this.state.siteId;
  84. const addValue = {
  85. userId: cellInfo.original.userId,
  86. patientId: patientId,
  87. siteId: siteId
  88. };
  89. getAddTrialPatient(addValue);
  90. if (this.state.siteId !== "" && this.state.patientId !== "") {
  91. let ifchange = [...this.state.ifchange];
  92. const ifchangeValue = [
  93. {
  94. bool: true,
  95. index: cellInfo.index
  96. }
  97. ];
  98. ifchange.push(ifchangeValue);
  99. this.setState({ ifchange });
  100. }
  101. };
  102. render() {
  103. return (
  104. <div>
  105. <ReactTable
  106. id="sessionTable"
  107. data={this.props.trialuser}
  108. colums = {
  109. [
  110. {
  111. Header: "Patient No",
  112. accessor: "patientId",
  113. minWidth: 180,
  114. filterable: false,
  115. Cell: this.renderEditable
  116. },
  117. {
  118. Header: "siteId",
  119. accessor: "siteId",
  120. minWidth: 180,
  121. filterable: false,
  122. Cell: this.renderEditsiteId
  123. }
  124. ]
  125. }
  126. defaultPageSize={20}
  127. className="-striped -highlight"
  128. minRows={0}
  129. />
  130. </div>
  131. );
  132. }
  133. }
  134. const mapStateToProp = state => ({
  135. trialuser: state.patientsListStore.trialuser,
  136. });
  137. const mapDispatchToProp = dispatch => ({
  138. getTrialList: self => dispatch(getTrialList(self)),
  139. getAddTrialPatient: addValue => dispatch(getAddTrialPatient(addValue))
  140. });
  141. export default connect(
  142. mapStateToProp,
  143. mapDispatchToProp
  144. )(DeviceList);

13.在输入框内设置回车键搜索,和onchange事件搜索

  1. {
  2. Header: "test",
  3. accessor: "test",
  4. maxWidth: 60,
  5. Filter: ({ filter, onChange }) => {
  6. return (
  7. <input
  8. type="text"
  9. style={{ width: "100%" }}
  10. onKeyPress={event => {
  11. if (event.keyCode === 13 || event.which === 13) {
  12. onChange(event.target.value);
  13. }
  14. }}
  15. onChange={event => {
  16. onChange(event.target.value);
  17. }}
  18. />
  19. );
  20. },
  21. filterMethod: (filter, row) => {
  22. return String(row[filter.id]).includes(filter.value);
  23. }
  24. },

14.实现头部不为文字,而是复选框或者其他组件

  1. // Header: "Actions",
  2. Header: props => {
  3. return (
  4. <Checkbox
  5. onChange={this.handleCheckAll}
  6. checked={this.state.checkedAll}
  7. name="selectAll"
  8. className="billCheck_all"
  9. />
  10. );
  11. },

15.实现在顶端增加页码和滚动条

showPaginationTop={true}

16.控制列的显示与隐藏

方法一:先定义一个state,然后在表格列表中通过this.state.hasColunm.displayColunm&&判断显示和隐藏,然后在数组末尾添加.filter(Boolean)

  1. constructor(props) {
  2. super(props);
  3. this.state = {
  4. hasColunm: {displayColunm: false}
  5. };
  6. }
  1. render() {
  2. return (
  3. <div className="device-list-container">
  4. <ReactTable
  5. data={
  6. this.props.searchList &&
  7. this.props.searchList.map(p => {
  8. return {
  9. ...p
  10. };
  11. })
  12. }
  13. filterable
  14. defaultFilterMethod={(filter, row) =>
  15. String(row[filter.id]) === filter.value
  16. }
  17. columns={[
  18. this.state.hasColunm.displayColunm&&
  19. {
  20. Header: "Email",
  21. accessor: "email",
  22. filterMethod: (filter, row) => {
  23. let rowfilterfullname = row._original.email
  24. ? row[filter.id].toLowerCase()
  25. : "";
  26. let filterfullname = filter.value.toLowerCase();
  27. return rowfilterfullname.includes(filterfullname);
  28. }
  29. },
  30. {
  31. columns: [
  32. {
  33. Header: "Cell Phone",
  34. accessor: "phone",
  35. maxWidth: 200,
  36. filterMethod: (filter, row) =>
  37. row._original.phone &&
  38. matchPhone(row[filter.id]).includes(filter.value)
  39. }
  40. ]
  41. }
  42. ].filter(Boolean)}
  43. defaultPageSize={20}
  44. className="-striped -highlight"
  45. minRows={0}
  46. />
  47. </div>
  48. );
  49. }
  50. }

方法二:

先定义一个state

  1. constructor(props) {
  2. super(props);
  3. this.state = {
  4. hasColunm: {emailDisplay: false}
  5. };
  6. }

再定义函数getColumns

  1. getColumns(this.state.hasColunm) {
  2. const columns = []
  3. for (const key in this.state.hasColumn) {
  4. switch (email) {
  5. case "emailDisplay":
  6. this.state.hasColunm[key]&&columns.push({
  7. Header: "Email",
  8. accessor: "email",
  9. filterMethod: (filter, row) => {
  10. return String(row[filter.id]).includes(filter.value);
  11. }
  12. })
  13. break;
  14. default:
  15. break;
  16. }
  17. }
  18. return columns
  19. }

然后再表格处写入函数

  1. render() {
  2. return (
  3. <div className="device-list-container">
  4. <ReactTable
  5. data={
  6. this.props.searchList &&
  7. this.props.searchList.map(p => {
  8. return {
  9. ...p
  10. };
  11. })
  12. }
  13. filterable
  14. defaultFilterMethod={(filter, row) =>
  15. String(row[filter.id]) === filter.value
  16. }
  17. columns={this.getColumns}
  18. defaultPageSize={20}
  19. className="-striped -highlight"
  20. minRows={0}
  21. />
  22. </div>
  23. );
  24. }
  25. }

17.react-table实现一个行的效果(暂时没找到更好的方法,如果有更好的方法,请留言评论,感谢)

通过添加footer,然后设置背景颜色统一,比如白色。然后将border取消

  1. columns={[
  2. {
  3. Header: "Key",
  4. accessor: "key",
  5. width: 200,
  6. style:{padding:0,border:0},
  7. filterMethod: (filter, row) => {
  8. return String(row[filter.id]).includes(filter.value);
  9. },
  10. Footer: (
  11. <span className="tableFooterRow"></span>
  12. )
  13. },
  14. {
  15. Header: "Value",
  16. accessor: "value",
  17. style:{padding:0,border:0},
  18. filterMethod: (filter, row) => {
  19. return String(row[filter.id]).includes(filter.value);
  20. },
  21. Footer: (
  22. <span className="tableFooterRow">TOTAL TIME</span>
  23. )
  24. }
.tableFooterRow{width: 100%;height: 50px;line-height: 50px;display: inline-table;color:white;font-weight:600;background-color:rgb(45, 1, 114)}

直接在column后面加Footer

18.报错:Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

解决办法:版本问题,卸载目前版本

npm uninstall react-table --save

重新安装指定版本的react-table

npm install react-table@6.10.3

19.react-table点击增加行

  1. import React, { Component } from "react";
  2. import ReactTable from "react-table";
  3. import "react-table/react-table.css";
  4. import "./App.css";
  5. const tableData = [
  6. { id: "1", value: "test1" },
  7. { id: "2", value: "test2" },
  8. { id: "3", value: "test3" },
  9. { id: "4", value: "test4" },
  10. { id: "5", value: "test5" },
  11. { id: "6", value: "test6" }
  12. ]
  13. class App extends Component {
  14. render() {
  15. return (
  16. <div className="boxlistcontainer">
  17. <ReactTable
  18. data={tableData}
  19. filterable
  20. defaultFilterMethod={(filter, row) =>
  21. String(row[filter.id]) === filter.value
  22. }
  23. columns={[
  24. {
  25. Header: "test",
  26. accessor: "id",
  27. sortable: false,
  28. filterable: false
  29. },
  30. {
  31. expander: true,
  32. Header: () => <strong>More</strong>,
  33. width: 65,
  34. Expander: ({ isExpanded, ...rest }) =>
  35. <div>
  36. {isExpanded
  37. ? <span>&#x2299;</span>
  38. : <span>&#x2295;</span>}
  39. </div>,
  40. style: {
  41. cursor: "pointer",
  42. fontSize: 25,
  43. padding: "0",
  44. textAlign: "center",
  45. userSelect: "none"
  46. }
  47. }
  48. ]}
  49. SubComponent={(v) => <div style={{ padding: '10px' }}>Hello {v.row._index}</div>}
  50. defaultPageSize={20}
  51. className="-striped -highlight"
  52. minRows={0}
  53. showPaginationTop={false}
  54. />
  55. </div>
  56. );
  57. }
  58. }
  59. export default App;

还可以使用semantic-ui-react实现该效果:https://blog.csdn.net/qq_37815596/article/details/102524063文章

20.对奇偶行进行不一样的样式设置

  1. /*(偶数行)*/
  2. .details_table_container .rt-tr-group:nth-child(even) {}
  3. /*(奇数行)*/
  4. .details_table_container .rt-tr-group:nth-child(odd) {background-image: linear-gradient(#044664,#0b184a,#044664);}

21.更改sort排序的那根线的颜色

源代码:

  1. .ReactTable .rt-thead .rt-th.-sort-asc, .ReactTable .rt-thead .rt-th.-sort-asc {
  2. box-shadow: inset 0 3px 0 0 rgba(255,255,255,0.6);
  3. }
  4. .ReactTable .rt-thead .rt-th.-sort-desc, .ReactTable .rt-thead .rt-td.-sort-desc {
  5. box-shadow: inset 0 -3px 0 0 rgba(0,0,0,0.6);
  6. }

修改之后:

  1. .details_table_container .rt-thead .rt-th.-sort-asc,
  2. .details_table_container .rt-thead .rt-td.-sort-asc {
  3. box-shadow: inset 0 3px 0 0 rgba(255, 255, 255) !important;
  4. }
  5. .details_table_container .rt-thead .rt-th.-sort-desc,
  6. .details_table_container .rt-thead .rt-td.-sort-desc {
  7. box-shadow: inset 0 -3px 0 0 rgba(255, 255, 255) !important;
  8. }

22.页数选择

defaultPageSize={20},结果如下方所示,仍然可以选择其他页数

pageSize={20},则不能再选择其他页数

showPageSizeOptions={false}可以实现不显示选择page size

23.页码切换事件

  1. onPageChange={this.onPageChange}
  2. onPageChange = (pageIndex) => {
  3.     console.log("pageIndex", pageIndex);
  4.   };

24.通过下拉选择执行查询

  1. filterMethod: (filter, row) => {
  2. if (filter.value === "all") {
  3. return true;
  4. }
  5. if (filter.value === "true") {
  6. return row[filter.id] >= 21;
  7. }
  8. return row[filter.id] < 21;
  9. },
  10. Filter: ({ filter, onChange }) =>
  11. <select
  12. onChange={event => onChange(event.target.value)}
  13. style={{ width: "100%" }}
  14. value={filter ? filter.value : "all"}
  15. >
  16. <option value="all">Show All</option>
  17. <option value="true">Can Drink</option>
  18. <option value="false">Can't Drink</option>
  19. </select>

 

 

 

 

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/140487
推荐阅读
相关标签
  

闽ICP备14008679号