react+ant design实现Table的增、删、改的示例代码


Posted in Javascript onDecember 27, 2018

本人小白一名,第一次学习react ,该资料为本人原创,采用的是react+ant design的Tabled的一个小demo,暂时只实现了增加,删除单行,多行删除有Bug,查看详情,呕心沥血耗时一周完成,禁止抄袭,转载请先留言,

1、main.jsx

import React from 'react';
import ReactDom from 'react-dom';
import ExampleTable from './ExampleTable.jsx'
 
ReactDom.render(
  <ExampleTable/>,
  document.getElementById('AppRoot')
);

2、ExampleTable.jsx, 注:记住引入antd.css, 否则Table组件无法正常显示。

import React from 'react';
import { Table,Button,Input,Icon,Popconfirm,Alert } from 'antd';
import AddUser from './AddUser.jsx'
import UserDetails from './UserDetails.jsx'
 
class ExampleTable extends React.Component {
  constructor(props) {//  构造函数
    super(props);
    this.state = {
      dataSource:[
        { key: 1, nid:1, name: 'tab', gender:'男' , age: 22, schoolname: '第一中学', description: '热爱班级活动,尊敬老师'},
        { key: 2, nid:2, name: 'shift', gender:'男' , age: 22, schoolname: '第一中学', description: '热爱班级活动,尊敬老师'},
        { key: 6, nid:6, name: 'ctrl', gender:'男' , age: 22, schoolname: '第一中学', description: '热爱班级活动,尊敬老师'},
        { key: 4, nid:4, name: 'caps lock', gender:'男' , age: 22, schoolname: '第一中学', description: '热爱班级活动,尊敬老师'},
        { key: 5, nid:5, name: 'enter', gender:'女' , age: 22, schoolname: '第一中学', description: '热爱班级活动,尊敬老师'}
      ],
      index : '',
      PersonCount :0,
      selectedRowKeys:[],
      selectedRows:[],
      record : 'abc'
    };
    this.onDelete = this.onDelete.bind(this);//绑定this,声明该方法需要绑定this, 直接在onClick中调用
    this.appendPerson = this.appendPerson.bind(this);
    this.handleSelectedDelete = this.handleSelectedDelete.bind(this);
    this.columns = [
      { title: '编号', dataIndex: 'nid', key: 'nid' ,width:'8%'},
      { title: '姓名', dataIndex: 'name', key: 'name' ,width:'15%'},
      { title: '性别', dataIndex: 'gender', key: 'gender' ,width:'10%'},
      { title: '年龄', dataIndex: 'age', key: 'age',width:'15%', },//render: (text, record, index) => (Math.floor(record.age/10))*10+"多岁"},
      { title: '学校', dataIndex: 'schoolname', key: 'schoolname',width:'15%' },
      { title: '在校表现', dataIndex: 'description', key: 'description' ,width:'20%'},
      { title: '操作', dataIndex: '', key: 'operation', width:'32%',render: (text,record,index)=>(
        <span>
           <Popconfirm title="删除不可恢复,你确定要删除吗?" >
                <a title="用户删除" className="mgl10"onClick={this.onDelete.bind(this,index)}>
                  <Icon type="delete"/></a>
           </Popconfirm>
          <span className="ant-divider"/>
          <UserDetails className="user_details" pass={record}/>
        </span>
      ) },
    ];
    }
 
  appendPerson(event){//得到子元素传过来的值
    let array = [];
    let count = 0;
    this.state.dataSource.forEach(function (element) {
      Object.keys(element).some(function (key) {
        if (key === 'nid') {
          count++;
          array[count] = element.nid
        }
      })
    })
    let sortData =array.sort();//对遍历得到的数组进行排序
    let MaxData = sortData[(this.state.dataSource.length)-1]//取最后一位下标的值
    event.key=MaxData+1;
    event.nid = MaxData+1;
    this.setState({
       dataSource:[...this.state.dataSource,event]
     })
 
  }
 
  onDelete(index){
      console.log(index)
      const dataSource = [...this.state.dataSource];
      dataSource.splice(index, 1);//index为获取的索引,后面的 1 是删除几行
      this.setState({ dataSource });
  }
 
  handleSelectedDelete(){
    if(this.state.selectedRowKeys.length>0){
      console.log(...this.state.selectedRowKeys)
      const dataSource = [...this.state.dataSource]
      dataSource.splice(this.state.selectedRows,this.state.selectedRows.length)
      this.setState({ dataSource });
    }
    else{
 
    }
  }
 
  render() {
    //联动选择框
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({//将选中的id和对象存入state
            selectedRowKeys:selectedRowKeys,
            selectedRows:selectedRows
        })
        console.log(selectedRows,selectedRowKeys)
      },
      onSelect: (record, selected, selectedRows) => {
        //console.log( record, ` selected :${selected}`,`selectedRows:${selectedRows}`);
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        //console.log(selected, selectedRows, changeRows);
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User',  // Column configuration not to be checked
      }),
    }
    return (
      <div className="div_body">
       <div id="div_left"></div>
       <div id="div-right">
         <div className="table_oftop">
           <Button type="primary" icon="search" style={{float:"right",marginLeft:10}}>查询</Button>
           <Input placeholder="input search text" style ={{width:300,float:"right"}}/>
           <div id="add_delete">
           <Button type="primary" className="selectedDelete" onClick={this.handleSelectedDelete}>删除所选</Button>
           <AddUser className="add_user_btn" callback={this.appendPerson}/>
           </div>
         </div>
        <Table columns={this.columns}
            dataSource={this.state.dataSource}
            className="table"
            rowSelection={rowSelection}
            scroll ={{y:400}}/>
 
      </div>
      </div>
    );
  }
}
module.exports = ExampleTable;

3、AddUser.jsx

import React from 'react';
import {Form,Input,Button,Select,Modal} from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
 
class AddUser extends React.Component{//在es6中定义一个AddUser类
   constructor(props){//构造函数
     super(props);
     this.state = {
       visible:false
     };
     this.handleAdd = this.handleAdd.bind(this);
     this.handleSubmit = this.handleSubmit.bind(this);
     this.handleOk = this.handleOk.bind(this)
     this.handleClear = this.handleClear.bind(this)
   }
  handleAdd() {
    this.setState({
      visible: true
    });
  }
  handleSubmit(e){//提交表单
    e.preventDefault();
     this.props.form.validateFieldsAndScroll((err,values)=>{
       if(!err){
         //console.log('接收的值:',values);
         this.setState({
           visible:false
         })
         this.props.form.resetFields();//清空提交的表单
         //当值传递到父元素后,通过回调函数触发appendPerson方法将参数values带到父元素
         this.props.callback(values);
       }
     })
  }
 
  handleClear(){
    this.props.form.resetFields();
  }
 
  handleOk() {
    this.setState({
      visible: false
      });
  }
  render(){
 
   const {getFieldDecorator} = this.props.form;
   const formItemLayout = {
     labelCol:{span : 6},
     wrapperCol:{span: 14}
   };
   const tailFormItemLayout = {
     wrapperCol: {
       span: 14,
       offset: 8
     }
   };
    return(
      <div>
        <Button type="primary" onClick={this.handleAdd}>添加用户</Button>
      <Modal title="新建用户" visible={this.state.visible} onCancel={this.handleOk} onOk={this.handleOk}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label = "用户名" hasFeedback>
            {getFieldDecorator('name', {
              rules:[{
                required:true,message:'请输入您的 name!'
              }]
            })(
              <Input placeholder="请输入您的用户名!"/>
            )}
            </FormItem>
          <FormItem {...formItemLayout} label="性别" hasFeedback>
            {getFieldDecorator('gender',{
              rules:[{
                required:true,message:'请输入您的 gender!'
              }]
            })(
              <Select placeholder="请选择您的性别">
                <Option value="男">男</Option>
                <Option value="女">女</Option>
              </Select>
        )}
          </FormItem>
          <FormItem {...formItemLayout} label="年龄" hasFeedback>
            {getFieldDecorator('age',{
              rules:[{required:true,message:'请选择您的 Age'
              }]
            })(
              <Select placeholder="请选择你您的年龄">
                  <Option value="26">26</Option>
                  <Option value="27">27</Option>
                  <Option value="28">28</Option>
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="就读学校" hasFeedback>
            {getFieldDecorator('schoolname',{
              rules:[{required:true,message:'请输入您的就读学校'}]
            })(
              <Input placeholder="请输入您的就读学校!"/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="在校表现" hasFeedback>
            {getFieldDecorator('description',{
              rules:[{required:true,message:'请输入您的在校表现'}]
            })(
              <Input type="textarea" rows={3} placeholder="请输入您的在校表现!"/>
            )}
          </FormItem>
          <FormItem {...tailFormItemLayout} style={{padding:10}}>
            <Button type="primary" htmlType="submit" size="large">提交</Button>
            <Button type="primary" size="large" onClick={this.handleClear}>重置</Button>
          </FormItem>
        </Form>
      </Modal>
      </div>
    )
  }
}
AddUser = Form.create()(AddUser); //解决了getFieldDecorator无法定义;
 
export default AddUser;

4、UserDetails.jsx

import React from 'react'
import {Modal,Button} from 'antd'
/*
 
 */
class UserDetails extends React.Component{
  constructor(props){
    super(props);
    this.state={
      visible:false
    }
    this.handlePopup = this.handlePopup.bind(this);
    this.handleOkOrCancel = this.handleOkOrCancel.bind(this);
  }
  handlePopup() {
    this.setState({
      visible: true
    });
  }
  handleOkOrCancel(){
    this.setState({
      visible: false
    });
  }
 
  render(){
    return(
      <div>
        <a onClick={this.handlePopup}>详情</a>
        <Modal title={this.props.pass.name} visible={this.state.visible}
            onOk=  {this.handleOkOrCancel} onCancel={this.handleOkOrCancel}>
          <p>姓名:  {this.props.pass.name}</p>
          <p>性别:  {this.props.pass.gender}</p>
          <p>年龄:   {this.props.pass.age}</p>
          <p>就读学校:  {this.props.pass.schoolname}</p>
          <p>在校表现:  {this.props.pass.description}</p>
        </Modal>
      </div>
    )
  }
 
}
 
export default UserDetails;

5、ExampleStyle.css

#div-right{
  width:80%;
  height:400px;
  text-Align:center;
  margin: 0 auto;
}
.div_body{
  margin-top: 0.5%;
}
.table_oftop{
  padding: 10px;
}
.selectedDelete{
  float: left;
  margin-left: 35%;
}
.add_user_btn{
  margin-left: auto;
}
.user_details{
  float: right;
}

ant design 官网地址:https://ant.design/components/table-cn/    看不懂的可以参考官方示例。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
jQuery toggleClass应用实例(附效果图)
Apr 06 Javascript
如何调试异步加载页面里包含的js文件
Oct 30 Javascript
jQuery中replaceWith()方法用法实例
Dec 25 Javascript
javascript事件的绑定基础实例讲解(34)
Feb 14 Javascript
详解Vue2.0 事件派发与接收
Sep 05 Javascript
vue在使用ECharts时的异步更新和数据加载详解
Nov 22 Javascript
详解Angular调试技巧之报错404(not found)
Jan 31 Javascript
vue input实现点击按钮文字增删功能示例
Jan 29 Javascript
详解关于微信setData回调函数中的坑
Feb 18 Javascript
利用d3.js实现蜂巢图表带动画效果
Sep 03 Javascript
layui-table对返回的数据进行转变显示的实例
Sep 04 Javascript
原生js实现简单轮播图
Oct 26 Javascript
React降级配置及Ant Design配置详解
Dec 27 #Javascript
详解Ant Design of React的安装和使用方法
Dec 27 #Javascript
利用Angular2的Observables实现交互控制的方法
Dec 27 #Javascript
angular 用Observable实现异步调用的方法
Dec 27 #Javascript
详解CommonJS和ES6模块循环加载处理的区别
Dec 26 #Javascript
vue-router beforeEach跳转路由验证用户登录状态
Dec 26 #Javascript
Vuerouter的beforeEach与afterEach钩子函数的区别
Dec 26 #Javascript
You might like
PHP脚本的10个技巧(5)
2006/10/09 PHP
微信公众平台接口开发入门示例
2014/12/24 PHP
PhpStorm2020.1 安装 debug - Postman 调用的详细教程
2020/08/17 PHP
输入自动提示搜索提示功能的javascript:sugggestion.js
2013/09/02 Javascript
javascript删除元素节点removeChild()用法实例
2015/05/26 Javascript
jQuery实现的手机发送验证码倒计时效果代码分享
2015/08/24 Javascript
javascript字符串函数汇总
2015/12/06 Javascript
基于BootStrap实现局部刷新分页实例代码
2016/08/08 Javascript
require、backbone等重构手机图片查看器
2016/11/17 Javascript
详解bootstrap的modal-remote两种加载方式【强化】
2017/01/27 Javascript
js实现3D图片环展示效果
2017/03/09 Javascript
angularJS模态框$modal实例代码
2017/05/27 Javascript
jQuery 实现图片的依次加载图片功能
2017/07/06 jQuery
vue使用mint-ui实现下拉刷新和无限滚动的示例代码
2017/11/06 Javascript
VUE实现可随意拖动的弹窗组件
2018/09/25 Javascript
Vue scrollBehavior 滚动行为实现后退页面显示在上次浏览的位置
2019/05/27 Javascript
解决Echarts2竖直datazoom滑动后显示数据不全的问题
2020/07/20 Javascript
关于angular引入ng-zorro的问题浅析
2020/09/09 Javascript
python使用cookielib库示例分享
2014/03/03 Python
Python中bisect的用法
2014/09/23 Python
Python循环语句中else的用法总结
2016/09/11 Python
Python实现字典按照value进行排序的方法分析
2017/12/23 Python
对Python字符串中的换行符和制表符介绍
2018/05/03 Python
python3实现163邮箱SMTP发送邮件
2018/05/22 Python
python读取和保存图片5种方法对比
2018/09/12 Python
python多进程间通信代码实例
2019/09/30 Python
浅谈Keras参数 input_shape、input_dim和input_length用法
2020/06/29 Python
解决运行django程序出错问题 'str'object has no attribute'_meta'
2020/07/15 Python
工程师自我评价怎么写
2013/09/19 职场文书
大二自我鉴定
2014/01/31 职场文书
资源工程专业毕业生求职信
2014/02/27 职场文书
党支部活动策划方案
2014/08/18 职场文书
房租涨价通知
2015/04/23 职场文书
四年级作文之植物
2019/09/20 职场文书
《废话连篇——致新手》——chinapizza
2022/04/05 无线电
python缺失值填充方法示例代码
2022/12/24 Python