后台管理系统常用到表单的增删改,这里也做了个封装

例如:user/index.js

  1. import React from 'react'
  2. import { Card, Button, Table, Form, Input, Checkbox,Select,Radio, Icon, message, Modal, DatePicker } from 'antd'
  3. import axios from '../../axios/index'
  4. import Utils from '../../utils/utils'
  5. import ETable from '../../components/ETable/index'
  6. import Moment from 'moment'
  7. const FormItem = Form.Item;
  8. const Option = Select.Option;
  9. const RadioGroup = Radio.Group;
  10. export default class User extends React.Component{
  11.  
  12. state = {
  13. list:[]
  14. }
  15.  
  16. params = {
  17. page:1
  18. }
  19.  
  20. requestList = ()=>{
  21. axios.ajax({
  22. url:'/table/list1',
  23. data:{
  24. params:{
  25. page:this.params.page
  26. }
  27. }
  28. }).then((res)=>{
  29. let _this = this;
  30. this.setState({
  31. list:res.result.list.map((item,index)=>{
  32. item.key=index
  33. return item;
  34. }),
  35. pagination:Utils.pagination(res,(current)=>{
  36. _this.params.page = current;
  37. _this.requestList();
  38. })
  39. })
  40. })
  41. }
  42.  
  43. componentDidMount(){
  44. this.requestList();
  45. }
  46.  
  47. // 操作员工
  48. handleOperator = (type)=>{
  49. let item = this.state.selectedItem;
  50. if(type =='create'){
  51. this.setState({
  52. title:'创建员工',
  53. isVisible:true,
  54. type
  55. })
  56. }else if(type=="edit" || type=='detail'){
  57. if(!item){
  58. Modal.info({
  59. title: '信息',
  60. content: '请选择一个用户'
  61. })
  62. return;
  63. }
  64. this.setState({
  65. title:type=='edit'?'编辑用户':'查看详情',
  66. isVisible:true,
  67. userInfo:item,
  68. type
  69. })
  70. }else if(type=="delete"){
  71. if(!item){
  72. Modal.info({
  73. title: '信息',
  74. content: '请选择一个用户'
  75. })
  76. return;
  77. }
  78. Utils.ui.confirm({
  79. text:'确定要删除此用户吗?',
  80. onOk:()=>{
  81. axios.ajax({
  82. url:'/user/delete',
  83. data:{
  84. params:{
  85. id:item.id
  86. }
  87. }
  88. }).then((res)=>{
  89. if(res.code ==0){
  90. this.setState({
  91. isVisible:false
  92. })
  93. this.requestList();
  94. }
  95. })
  96. }
  97. })
  98. }
  99. }
  100.  
  101. handleSubmit = ()=>{
  102. let type = this.state.type;
  103. let data = this.userForm.props.form.getFieldsValue();
  104. axios.ajax({
  105. url:type == 'create'?'/user/add':'/user/edit',
  106. data:{
  107. params:{
  108. ...data
  109. }
  110. }
  111. }).then((res)=>{
  112. if(res.code ==0){
  113. this.setState({
  114. isVisible:false
  115. })
  116. this.requestList();
  117. }
  118. })
  119. }
  120.  
  121. render(){
  122. const columns = [{
  123. title: 'id',
  124. dataIndex: 'id'
  125. }, {
  126. title: '用户名',
  127. dataIndex: 'username'
  128. }, {
  129. title: '性别',
  130. dataIndex: 'sex',
  131. render(sex){
  132. return sex ==1 ?'男':'女'
  133. }
  134. }, {
  135. title: '状态',
  136. dataIndex: 'state',
  137. render(state){
  138. let config = {
  139. '1':'咸鱼一条',
  140. '2':'风华浪子',
  141. '3':'北大才子一枚',
  142. '4':'百度FE',
  143. '5':'创业者'
  144. }
  145. return config[state];
  146. }
  147. },{
  148. title: '爱好',
  149. dataIndex: 'interest',
  150. render(interest){
  151. let config = {
  152. '1':'游泳',
  153. '2':'打篮球',
  154. '3':'踢足球',
  155. '4':'跑步',
  156. '5':'爬山',
  157. '6':'骑行',
  158. '7':'桌球',
  159. '8':'麦霸'
  160. }
  161. return config[interest];
  162. }
  163. },{
  164. title: '婚姻',
  165. dataIndex: 'isMarried',
  166. render(isMarried){
  167. return isMarried?'已婚':'未婚'
  168. }
  169. },{
  170. title: '生日',
  171. dataIndex: 'birthday'
  172. },{
  173. title: '联系地址',
  174. dataIndex: 'address'
  175. },{
  176. title: '早起时间',
  177. dataIndex: 'time'
  178. }
  179. ];
  180. return (
  181. <div>
  182. <Card>
  183. <Form layout="inline">
  184. <FormItem>
  185. <Input placeholder="请输入用户名"/>
  186. </FormItem>
  187. <FormItem>
  188. <Input type="password" placeholder="请输入密码"/>
  189. </FormItem>
  190. <FormItem>
  191. <Button type="primary">登 录</Button>
  192. </FormItem>
  193. </Form>
  194. </Card>
  195. <Card style={{marginTop:10}}>
  196. <Button type="primary" icon="plus" onClick={()=>this.handleOperator('create')}>创建员工</Button>
  197. <Button icon="edit" onClick={()=>this.handleOperator('edit')}>编辑员工</Button>
  198. <Button onClick={()=>this.handleOperator('detail')}>员工详情</Button>
  199. <Button type="danger" icon="delete" onClick={()=>this.handleOperator('delete')}>删除员工</Button>
  200. </Card>
  201. <div className="content-wrap">
  202. <ETable
  203. columns={columns}
  204. updateSelectedItem={Utils.updateSelectedItem.bind(this)}
  205. selectedRowKeys={this.state.selectedRowKeys}
  206. dataSource={this.state.list}
  207. pagination={this.state.pagination}
  208. />
  209. </div>
  210. <Modal
  211. title={this.state.title}
  212. visible={this.state.isVisible}
  213. onOk={this.handleSubmit}
  214. width={800}
  215. onCancel={()=>{
  216. this.userForm.props.form.resetFields();
  217. this.setState({
  218. isVisible:false,
  219. userInfo:''
  220. })
  221. }}
  222. >
  223. <UserForm userInfo={this.state.userInfo} type={this.state.type} wrappedComponentRef={(inst) => this.userForm = inst }/>
  224. </Modal>
  225. </div>
  226. );
  227. }
  228. }
  229. class UserForm extends React.Component{
  230.  
  231. getState = (state)=>{
  232. return {
  233. '1':'咸鱼一条',
  234. '2':'风华浪子',
  235. '3':'北大才子一枚',
  236. '4':'百度FE',
  237. '5':'创业者'
  238. }[state]
  239. }
  240.  
  241. render(){
  242. const { getFieldDecorator } = this.props.form;
  243. const formItemLayout = {
  244. labelCol: {span: 5},
  245. wrapperCol: {span: 16}
  246. };
  247. const userInfo = this.props.userInfo || {};
  248. const type = this.props.type;
  249. return (
  250. <Form layout="horizontal">
  251. <FormItem label="姓名" {...formItemLayout}>
  252. {
  253. userInfo && type=='detail'?userInfo.username:
  254. getFieldDecorator('user_name',{
  255. initialValue:userInfo.username
  256. })(
  257. <Input type="text" placeholder="请输入姓名"/>
  258. )
  259. }
  260. </FormItem>
  261. <FormItem label="性别" {...formItemLayout}>
  262. {
  263. userInfo && type=='detail'?userInfo.sex==1?'男':'女':
  264. getFieldDecorator('sex',{
  265. initialValue:userInfo.sex
  266. })(
  267. <RadioGroup>
  268. <Radio value={1}>男</Radio>
  269. <Radio value={2}>女</Radio>
  270. </RadioGroup>
  271. )}
  272. </FormItem>
  273. <FormItem label="状态" {...formItemLayout}>
  274. {
  275. userInfo && type=='detail'?this.getState(userInfo.state):
  276. getFieldDecorator('state',{
  277. initialValue:userInfo.state
  278. })(
  279. <Select>
  280. <Option value={1}>咸鱼一条</Option>
  281. <Option value={2}>风华浪子</Option>
  282. <Option value={3}>北大才子一枚</Option>
  283. <Option value={4}>百度FE</Option>
  284. <Option value={5}>创业者</Option>
  285. </Select>
  286. )}
  287. </FormItem>
  288. <FormItem label="生日" {...formItemLayout}>
  289. {
  290. userInfo && type=='detail'?userInfo.birthday:
  291. getFieldDecorator('birthday',{
  292. initialValue:Moment(userInfo.birthday)
  293. })(
  294. <DatePicker />
  295. )}
  296. </FormItem>
  297. <FormItem label="联系地址" {...formItemLayout}>
  298. {
  299. userInfo && type=='detail'?userInfo.address:
  300. getFieldDecorator('address',{
  301. initialValue:userInfo.address
  302. })(
  303. <Input.TextArea rows={3} placeholder="请输入联系地址"/>
  304. )}
  305. </FormItem>
  306. </Form>
  307. );
  308. }
  309. }
  310. UserForm = Form.create({})(UserForm);

ETable/index.js

  1. import React from 'react'
  2. import Utils from '../../utils/utils'
  3. import {Table} from 'antd'
  4. import "./index.less"
  5. export default class ETable extends React.Component {
  6.  
  7. state = {}
  8. //处理行点击事件
  9. onRowClick = (record, index) => {
  10. let rowSelection = this.props.rowSelection;
  11. if(rowSelection == 'checkbox'){
  12. let selectedRowKeys = this.props.selectedRowKeys;
  13. let selectedIds = this.props.selectedIds;
  14. let selectedItem = this.props.selectedItem || [];
  15. if (selectedIds) {
  16. const i = selectedIds.indexOf(record.id);
  17. if (i == -1) {//避免重复添加
  18. selectedIds.push(record.id)
  19. selectedRowKeys.push(index);
  20. selectedItem.push(record);
  21. }else{
  22. selectedIds.splice(i,1);
  23. selectedRowKeys.splice(i,1);
  24. selectedItem.splice(i,1);
  25. }
  26. } else {
  27. selectedIds = [record.id];
  28. selectedRowKeys = [index]
  29. selectedItem = [record];
  30. }
  31. this.props.updateSelectedItem(selectedRowKeys,selectedItem || {},selectedIds);
  32. }else{
  33. let selectKey = [index];
  34. const selectedRowKeys = this.props.selectedRowKeys;
  35. if (selectedRowKeys && selectedRowKeys[0] == index){
  36. return;
  37. }
  38. this.props.updateSelectedItem(selectKey,record || {});
  39. }
  40. };
  41.  
  42. // 选择框变更
  43. onSelectChange = (selectedRowKeys, selectedRows) => {
  44. let rowSelection = this.props.rowSelection;
  45. const selectedIds = [];
  46. if(rowSelection == 'checkbox'){
  47. selectedRows.map((item)=>{
  48. selectedIds.push(item.id);
  49. });
  50. this.setState({
  51. selectedRowKeys,
  52. selectedIds:selectedIds,
  53. selectedItem: selectedRows[0]
  54. });
  55. }
  56. this.props.updateSelectedItem(selectedRowKeys,selectedRows[0],selectedIds);
  57. };
  58.  
  59. onSelectAll = (selected, selectedRows, changeRows) => {
  60. let selectedIds = [];
  61. let selectKey = [];
  62. selectedRows.forEach((item,i)=> {
  63. selectedIds.push(item.id);
  64. selectKey.push(i);
  65. });
  66. this.props.updateSelectedItem(selectKey,selectedRows[0] || {},selectedIds);
  67. }
  68.  
  69. getOptions = () => {
  70. let p = this.props;
  71. const name_list = {
  72. "订单编号":170,
  73. "车辆编号":80,
  74. "手机号码":96,
  75. "用户姓名":70,
  76. "密码":70,
  77. "运维区域":300,
  78. "车型":42,
  79. "故障编号":76,
  80. "代理商编码":97,
  81. "角色ID":64
  82. };
  83. if (p.columns && p.columns.length > 0) {
  84. p.columns.forEach((item)=> {
  85. //开始/结束 时间
  86. if(!item.title){
  87. return
  88. }
  89. if(!item.width){
  90. if(item.title.indexOf("时间") > -1 && item.title.indexOf("持续时间") <){
  91. item.width = 132
  92. }else if(item.title.indexOf("图片") > -1){
  93. item.width = 86
  94. }else if(item.title.indexOf("权限") > -1 || item.title.indexOf("负责城市") > -1){
  95. item.width = '40%';
  96. item.className = "text-left";
  97. }else{
  98. if(name_list[item.title]){
  99. item.width = name_list[item.title];
  100. }
  101. }
  102. }
  103. item.bordered = true;
  104. });
  105. }
  106. const { selectedRowKeys } = this.props;
  107. const rowSelection = {
  108. type: 'radio',
  109. selectedRowKeys,
  110. onChange: this.onSelectChange,
  111. onSelect:(record, selected, selectedRows)=>{
  112. console.log('...')
  113. },
  114. onSelectAll:this.onSelectAll
  115. };
  116. let row_selection = this.props.rowSelection;
  117. // 当属性未false或者null时,说明没有单选或者复选列
  118. if(row_selection===false || row_selection === null){
  119. row_selection = false;
  120. }else if(row_selection == 'checkbox'){
  121. //设置类型未复选框
  122. rowSelection.type = 'checkbox';
  123. }else{
  124. //默认未单选
  125. row_selection = 'radio';
  126. }
  127. return <Table
  128. className="card-wrap page-table"
  129. bordered
  130. {...this.props}
  131. rowSelection={row_selection?rowSelection:null}
  132. onRow={(record,index) => ({
  133. onClick: ()=>{
  134. if(!row_selection){
  135. return;
  136. }
  137. this.onRowClick(record,index)
  138. }
  139. })}
  140. />
  141. };
  142. render = () => {
  143. return (
  144. <div>
  145. {this.getOptions()}
  146. </div>
  147. )
  148. }
  149. }

ETable/index.scss

  1. @import '../../style/default';
  2. .ant-table{
  3. &-thead > tr > th,
  4. &-tbody > tr > td{
  5. padding:14px 6px;
  6. text-align:center;
  7. }
  8. .ant-table-selection-column{
  9. min-width:42px!important;
  10. width:42px!important;;
  11. }
  12.  
  13. .text-center {
  14. text-align: center;
  15. }
  16. .text-left {
  17. text-align: left;
  18. }
  19. &.ant-table-middle{
  20. &-thead > tr > th,
  21. &-tbody > tr > td{
  22. padding:10px 6px;
  23. }
  24. }
  25. &.ant-table-small{
  26. &-thead > tr > th,
  27. &-tbody > tr > td{
  28. padding:8px 6px;
  29. }
  30. }
  31. }
  32. .ant-table-pagination{
  33. padding:0 20px;
  34. }

utils/utils.js

  1. import React from 'react';
  2. import { Select } from 'antd'
  3. const Option = Select.Option;
  4. export default {
  5. formateDate(time){
  6. if(!time)return '';
  7. let date = new Date(time);
  8. return date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();
  9. },
  10. pagination(data,callback){
  11. return {
  12. onChange:(current)=>{
  13. callback(current)
  14. },
  15. current:data.result.page,
  16. pageSize:data.result.page_size,
  17. total: data.result.total_count,
  18. showTotal:()=>{
  19. return `共${data.result.total_count}条`
  20. },
  21. showQuickJumper:true
  22. }
  23. },
  24. // 格式化金额,单位:分(eg:430分=4.30元)
  25. formatFee(fee, suffix = '') {
  26. if (!fee) {
  27. return 0;
  28. }
  29. return Number(fee).toFixed(2) + suffix;
  30. },
  31. // 格式化公里(eg:3000 = 3公里)
  32. formatMileage(mileage, text) {
  33. if (!mileage) {
  34. return 0;
  35. }
  36. if (mileage >= 1000) {
  37. text = text || " km";
  38. return Math.floor(mileage / 100) / 10 + text;
  39. } else {
  40. text = text || " m";
  41. return mileage + text;
  42. }
  43. },
  44. // 隐藏手机号中间4位
  45. formatPhone(phone) {
  46. phone += '';
  47. return phone.replace(/(\d{3})\d*(\d{4})/g, '$1***$2')
  48. },
  49. // 隐藏身份证号中11位
  50. formatIdentity(number) {
  51. number += '';
  52. return number.replace(/(\d{3})\d*(\d{4})/g, '$1***********$2')
  53. },
  54. getOptionList(data){
  55. if(!data){
  56. return [];
  57. }
  58. let options = [] //[<Option value="0" key="all_key">全部</Option>];
  59. data.map((item)=>{
  60. options.push(<Option value={item.id} key={item.id}>{item.name}</Option>)
  61. })
  62. return options;
  63. },
  64. /**
  65. * ETable 行点击通用函数
  66. * @param {*选中行的索引} selectedRowKeys
  67. * @param {*选中行对象} selectedItem
  68. */
  69. updateSelectedItem(selectedRowKeys, selectedRows, selectedIds) {
  70. if (selectedIds) {
  71. this.setState({
  72. selectedRowKeys,
  73. selectedIds: selectedIds,
  74. selectedItem: selectedRows
  75. })
  76. } else {
  77. this.setState({
  78. selectedRowKeys,
  79. selectedItem: selectedRows
  80. })
  81. }
  82. },
  83. }

axios/index.js

  1. import JsonP from 'jsonp'
  2. import axios from 'axios'
  3. import { Modal } from 'antd'
  4. export default class Axios {
  5. static jsonp(options) {
  6. return new Promise((resolve, reject) => {
  7. JsonP(options.url, {
  8. param: 'callback'
  9. }, function (err, response) {
  10. if (response.status == 'success') {
  11. resolve(response);
  12. } else {
  13. reject(response.messsage);
  14. }
  15. })
  16. })
  17. }
  18.  
  19. static ajax(options){
  20. let loading;
  21. if (options.data && options.data.isShowLoading !== false){
  22. loading = document.getElementById('ajaxLoading');
  23. loading.style.display = 'block';
  24. }
  25. let baseApi = 'https://www.easy-mock.com/mock/5a7278e28d0c633b9c4adbd7/api';
  26. return new Promise((resolve,reject)=>{
  27. axios({
  28. url:options.url,
  29. method:'get',
  30. baseURL:baseApi,
  31. timeout:5000,
  32. params: (options.data && options.data.params) || ''
  33. }).then((response)=>{
  34. if (options.data && options.data.isShowLoading !== false) {
  35. loading = document.getElementById('ajaxLoading');
  36. loading.style.display = 'none';
  37. }
  38. if (response.status == '200'){
  39. let res = response.data;
  40. if (res.code == '0'){
  41. resolve(res);
  42. }else{
  43. Modal.info({
  44. title:"提示",
  45. content:res.msg
  46. })
  47. }
  48. }else{
  49. reject(response.data);
  50. }
  51. })
  52. });
  53. }
  54. }

效果

getFieldDecorator用法(三)——Table增删改的更多相关文章

  1. Jquery Easy UI初步学习(三)数据增删改

    第二篇只是学了加载用datagrid加载数据,数据的增删改还没有做,今天主要是解决这个问题了. 在做增删改前需要弹出对应窗口,这就需要了解一下EasyUi的弹窗控件. 摘自:http://philoo ...

  2. MySQL在DOS界面对database和table增删改查

    昨天新接触MySQL,学习了一些内容,今天过来复习一下.(吐槽一下:安装个MySQL耗费老子半天时间!!) 学习了一下,大概知道了对数据库基本的增删改查,增add,删drop,改alter,查show ...

  3. JavaJDBC【三、增删改查】

    获取数据库连接后,可进行增删改查操作 语句生成: Statement s = con.createStatement(sql); //生成语句 PreparedStatement ps = (Prep ...

  4. Maybatis的一些总结(三:增删改查)

    回顾一个点 之前不懂这句: UserMapper userMapper = sqlSession.getMapper(UserMapper.class); 现在理解了一点点,相当于实现了userMap ...

  5. 2017年12月13日 LinQ用法基本的增删改查

    LinQ是什么? LinQ是语言集成的查询,是用于C#跟Vb的扩展语言 LinQ的用法 新建一个App_Code文件夹,在文件夹下添加一个数据LinQ to SQL类,可以直接直接点击服务器管理器然后 ...

  6. table增删改查操作--jq

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  7. java连接mysql数据库 三 实现增删改查操作

    同以前一样,先写一个数据库打开和关闭操作类 public class DBConnection { String driver = "com.mysql.jdbc.Driver"; ...

  8. MyBatis数据持久化(三)增删改查

    上篇文章中我们使用mybatis成功建立数据库会话,并从表中查询出相应的数据,本文在此基础上介绍MyBatis另外几种操作,即插入.修改.删除记录. 1.修改User.xml文件,增加几条sql语句: ...

  9. 【讲义提纲】以一个实战新闻cms增删改查demo为例,给学院国创队伍培训php

    PHP实战基础——以一个新闻cms的增删改查为例 一.        环境配置 二.        数据库创建 三.        增删改查demo 连接数据库 <?php $link=mysq ...

随机推荐

  1. squoosh

    谷歌在线压缩图片

  2. 汉明码(hamming code)

    hamming code用于磁盘RAID 2中, 关于汉明码的讲解可以看这篇博文,介绍的很详细.最重要是最后的结论: 汉明码属于分组奇偶校验,P4P2P1=000,说明接收方生成的校验位和收到的校验位 ...

  3. 用php连接数据库,并执行数据库操作

    1,建立与数据库之间的连接 (能通过php代码执行一个SQL语句得到查询的结果) <?php mysqli_connect(' , 'demo01'); 这里要注意两个问题: ①mysqli 是 ...

  4. iframe标签(页面嵌套)

    本文链接:https://blog.csdn.net/weixin_44540236/article/details/92760494 两个不同的页面但是它们的基本框架都是一样,每点击一次左边的导航栏 ...

  5. 阿里云 elasticsearch 增删改查

    kibana 控制台 # 查询所有数据 GET /yixiurds_dev/_search { "query": { "match_all": { } } } ...

  6. 第三篇.python编辑器和集成环境01

    修改python的镜像源 使用pip可以提高网速 \Lib\site-packages\pip\models\index.py文件,将PYPI的值改为你所需要的镜像源即可,例如改为豆瓣镜像源: #Py ...

  7. Linux计划任务与压缩归档

    计划任务分为两种形式 第一种:定时性的:也就是例行,每隔一定的周期就要重复来做这个任务. 第二种:突发性的:临时决定,只执行一次的任务. 用到的命令有两个 at:它是一个可以处理仅执行一次的任务就结束 ...

  8. linux基础—课堂随笔010_系统启动和内核管理

    系统启动和内核管理 Linux: kernel+rootfs kernel: 进程管理.内存管理.网络管理.驱动程序.文件系统.安全功能 rootfs:程序和glibc 库:函数集合, functio ...

  9. 版本控制工具 svn 一

    一.svn 概述 1).svn的作用 1.多人协作开发:2.远程控制:3.版本控制 2).软件控制管理工具发展之路 SCM:软件配置管理,所谓的软件配置管理实际就是软件源代码的 控制与管理. CVS: ...

  10. nagios-调用脚本

    在自已编写监控插件之前我们首先需要对nagios监控原理有一定的了解 Nagios的功能是监控服务和主机,但是他自身并不包括这部分功能,所有的监控.检测功能都是通过各种插件来完成的. 启动Nagios ...