在React中插入可编辑的table表格

在实际项目中会涉及到很多有关表格的问题,而不仅仅是将数据渲染在页面上。
1.表格中的数据可以编辑,input框,下拉框等。
2.有时候对输入的数据也会有限制,如保留两位小数或者输入正整数等。
3.在没有数据情况下,增加可编辑的表格,进行数据维护。

以下展示的代码,包含了上面提及的情况,可直接复制代码运行

(1) 在无数据的情况下,新增按钮可以点击,点击新增按钮,一次最多增加3行可编辑行,新增之后,按钮为禁止状态

在React中插入可编辑的table表格_第1张图片

(2) 有数据的情况下,数据渲染在页面上,表格可编辑。(默认最多显示3行,如果数据不足3组,可判断一下补充至3行,这种情况下面代码中不包含)

在React中插入可编辑的table表格_第2张图片

  • 代码分布
	├── table/                                                                   
	│     ├── index.less                    
	│     ├── state.js                         
	│     ├── addTable.js                              
	│     ├──mock.json    
  • addTable.js table组件部分
import React from 'react'
import {
      observer } from 'mobx-react'
import {
      Table, Input, Select, Form, Button } from 'antd'
import $state from './state'

const {
      Option } = Select
const {
      Item } = Form
@observer
class ThirdTable extends React.Component {
     
  constructor(props) {
     
    super(props)
    this.state = {
     }
  }

  componentDidMount() {
     
    $state.queryDetails()
    this.isDisable()
  }
  componentDidUpdate() {
     
    this.isDisable()
  }

  //判断按钮是否是禁止状态
  isDisable = () => {
     
    let source = [];
    source = $state.topThreeDTO || []

    if (!source.length) {
     
      $state.isDisableFlag1 = false
    } else {
     
      $state.isDisableFlag1 = true
    }
    //优化后为下面这样
    $state.isDisableFlag1=!!source.length
  }

  init = () => {
     
    const {
      getFieldDecorator } = this.props.form
    const projectArr = [
      {
      name: "绿州", num: "100" },
      {
      name: "长岛", num: "101" },
      {
      name: "紫荆", num: "102" }
    ]

    this.columns = [
      {
     
        title: '排名',
        dataIndex: 'orderNum',
      },
      {
     
        title: '项目名称',
        dataIndex: 'projectName',
        width: '40%',
        render: (text, record) => {
     
          console.log(`projectName.${
       record.orderNum}`)//projectName.1 需要保证唯一性
          return <Item>
            {
          
              getFieldDecorator(`projectName.${
       record.orderNum}`, {
     
                initialValue: text && text.num
              })
                (
                  <Select>
                    {
     
                      projectArr.length > 0 && projectArr.map((item, index) => {
     
                        return <Option style={
     {
     width:120}} value={
     item.num} key={
     index}>			{
     item.name}</Option>
                      })
                    }
                  </Select>
                )
            }
          </Item>
        }
      },
      {
     
        title: '均价(元/㎡)',
        dataIndex: 'averagePrice',
        width: '40%',
        render: (text, record) => {
     
          return <Item >
            {
     
              getFieldDecorator(`averagePrice.${
       record.orderNum}`, {
     
                rules: [{
     
                  pattern: new RegExp(/^[1-9]\d*$/),
                  message: '请输入正整数!'
                }],
                /*rules: [{
                    pattern: new RegExp(/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/),

                    message: '小数点后最多保留两位小数!'
                  }],*/
                initialValue: text
              })
                (
                  <Input />
                )
            }
          </Item>
        }
      }
    ];
  }
  //新增表格
  handleAddRow = () => {
     
    const newData = [
      {
     
        orderNum: '1',
        projectName: {
      name: "", num: "" },
        averagePrice: "",
      },
      {
     
        orderNum: '2',
        projectName: {
      name: "", num: "" },
        averagePrice: "",
      },
      {
     
        orderNum: '3',
        projectName: {
      name: "", num: "" },
        averagePrice: "",
      }
    ]

    $state.topThreeDTO = newData
    $state.isDisableFlag1 = true
  }
  render() {
     
    this.init()
    return (
    //data={
     { flag: $state.renderFlag }} 强制渲染表格的一种方法
      <div data={
     {
      flag: $state.renderFlag }}>
        <h1 className='table-title'>
          前三名
          </h1>
        <Button className={
     $state.isDisableFlag1 ? '' : 'button-in-step'} disabled={
     $state.isDisableFlag1} onClick={
     this.handleAddRow}>新增</Button>
        <Table
          className="plain-gray-table"
          dataSource={
     $state.topThreeDTO}
          columns={
     this.columns}
          pagination={
     false}
          bordered
          rowKey={
     record => record.orderNum}
        />
      </div>
    )
  }
}

export default Form.create(
  {
     
    onValuesChange(props, changeValues, allValues) {
      }
    
  }
)(ThirdTable)
  • mock.json 模拟的数据
{
     
  "code": 200,
  "modelList": [
    {
     
      "orderNum": "1",
      "projectName": {
      "name": "绿州", "num": "100" },
      "averagePrice": "10000"
    },
    {
     
      "orderNum": "2",
      "projectName": {
      "name": "长岛", "num": "101" },
      "averagePrice": "13000"
    },
    {
     
      "orderNum": "3",
      "projectName": {
      "name": "紫荆", "num": "102" },
      "averagePrice": "17000"
    }  
  ]
}

  • state.js 数据操作
import {
      observable, action, toJS } from 'mobx'
import $mock from './mock.json'

class State {
     
  @observable topThreeDTO = []//均价前三名
  @observable isDisableFlag1 = true//表格新增按钮是否禁用

  @action queryDetails = async () => {
     
    const res = await $mock
    console.log(res);

    if (res.code == 200) {
     
      this.topThreeDTO = res.modelList
    }}
}
export default new State();
  • index.less
.ant-select.ant-select-enabled {
     
  width:100%;
}
.table-title {
     
  color:red;
}
.plain-gray-table.ant-table-wrapper {
     
		margin-top: 20px;
		thead > tr > th {
     
			background: #cde6ff;
			// color: #0D152A;
			font-weight: 700;
			text-align: left;
			padding: 12px 16px;
		}
		thead > tr:first-child > th:first-child {
     
			border-top-left-radius: 0;
		}
		thead > tr:first-child > th:last-child {
     
			border-top-right-radius: 0;
		}
		tbody > tr:nth-child(odd) {
     
			background: #fff;
		}
		tbody > tr:nth-child(even) {
     
			background: #f6f7fa;
		}
		tbody > tr > td {
     
			text-align: center;
			padding: 7px 16px;
			color: #0d152a;
			button {
     
				color: #5c8ae5;
				background: #d9ecff;
				border-radius: 10px;
				border: none;
				padding: 0 12px;
			}
		}
		.ant-table-tbody > tr.ant-table-row-hover:not(.ant-table-expanded-row) > td,
		.ant-table-tbody > tr:hover:not(.ant-table-expanded-row) > td {
     
			background: #e1e6ef;
		}
	}

你可能感兴趣的:(Table,react)