今天在用React的UI库Antd 4.x版本 里的表单和表格配合写一个修改的需求,由于每次点击修改要拿到原来的值,所以需要用到表单的一些Api
表单设置值的API
//表单
<Form ref={this.formRef}>
<Item name="categoryName" label="分类名" hasFeedback rules={[{ required: true, message: '分类名不可以为空!' }]}>
<Input allowClear placeholder="请输入分类名!" onChange={this.addonChange} />
</Item>
</Form>
//相关API
this.formRef.current.setFieldsValue({
categoryName: name,//categoryName是对应的表单中Item的name字段 这里的name是方法拿到的变量
})
表单清空值的API
this.formRef.current.resetFields() //清空
报错 Uncaught TypeError: Cannot read property ‘setFieldsValue’ of null
报错原因:对话框模块还没显示,也就是表单还没挂载就调用了setFieldsValue,所以报错
附成功的源码
//列表页面
import React, { Component } from 'react'
import { Button, message, Table } from 'antd'
import { PlusCircleOutlined } from '@ant-design/icons'
import './css.less'
import { reqCategory } from '../../api'
import Modal from './components/Modal/view'
export default class CategoryComponent extends Component {
formRef = React.createRef()
constructor(props) {
super(props)
this.state = {
dataSource: [],
pageNumber: 1,
pageSize: 5,
isModalVisible: false,
modalType: '',
categoryId: 0,
}
}
componentWillMount() {
this.getListData()
}
componentWillUpdate(nextProps, nexpState) {
let { isModalVisible } = this.state
if (isModalVisible !== nexpState.isModalVisible) {
this.getListData()
}
}
getListData = async () => {
let result = await reqCategory()
if (result) {
let { status, data, msg } = result
if (status !== 0) message.error(msg, 1)
this.setState({
dataSource: data,
})
}
}
render() {
let { dataSource, pageNumber, pageSize } = this.state
return (
<div style={{ width: '100%' }}>
<div className={'categoryHeader'}>
<Button style={{ float: 'right' }} type={'primary'} icon={<PlusCircleOutlined />} onClick={() => this.oppModal('新增')}>
添加
</Button>
<div style={{ clear: 'both' }} />
</div>
<div className={'categoryBottom'}>
<Table
bordered
rowKey="_id"
dataSource={dataSource}
columns={[
{
title: <span style={{ fontWeight: 700 }}>分类名</span>,
dataIndex: 'name',
align: 'left',
key: '_id',
},
{
title: <span style={{ fontWeight: 700 }}>操作</span>,
key: '_id',
align: 'center',
width: '20%',
render: reload => {
return (
<Button type={'link'} onClick={() => this.oppModal('修改', reload)}>
修改分类
</Button>
)
},
},
]}
pagination={{
current: pageNumber,
pageSize: pageSize,
showQuickJumper: true,
onChange: this.onPageChange,
}}
/>
</div>
{this.showModal(this.state.isModalVisible, dataSource)}
</div>
)
}
onPageChange = (pageNumber, pageSize) => {
this.setState({
pageNumber,
pageSize,
})
}
oppModal = (type, data) => {
if (data) {
let { _id, name } = data
this.setState({
isModalVisible: true,
categoryId: _id,
categoryName: name,
modalType: type,
})
} else {
this.setState({
isModalVisible: true,
modalType: type,
categoryName: undefined,
})
}
}
closeModal = () => {
this.setState({
isModalVisible: false,
})
}
showModal = (flag, data) => {
let { categoryId, categoryName, modalType } = this.state
if (flag) {
return (
<Modal flag={flag} dataSource={data} dataSourceFun={value => this.setState({ dataSource: value })} closeModal={() => this.closeModal()} id={categoryId} name={categoryName} type={modalType} />
)
}
}
}
将对话框表单封装成独立的组件即可避免报错
//对话框表单组件
import React, { Component } from 'react'
import { Modal, Input, Form, message } from 'antd'
import { reqAddCategory, reqPutCategory } from '../../../../api'
const { Item } = Form
export default class ModalComponent extends Component {
formRef = React.createRef()
constructor(props) {
super(props)
this.state = {
flag: false,
type: '',
id: 0,
}
}
componentWillMount() {
let { flag, id, name, type, dataSource } = this.props
this.setState({
flag,
id,
name,
type,
dataSource,
})
}
componentDidMount() {
let { name } = this.state
this.formRef.current.setFieldsValue({ name })
}
closeClear = () => {
let { closeModal } = this.props
this.formRef.current.resetFields() //清空表单
closeModal()
}
render() {
let { flag, type } = this.state
return (
<Modal title={type} visible={flag} onOk={this.handleOk} onCancel={() => this.closeClear()} cancelText="取消" okText="确定">
<Form ref={this.formRef}>
<Item name="name" label="分类名" hasFeedback rules={[{ required: true, message: '分类名不可以为空!' }]}>
<Input allowClear placeholder="请输入分类名!" onChange={this.addonChange} />
</Item>
</Form>
</Modal>
)
}
addonChange = e => {
this.setState({
name: e.target.value,
})
}
handleOk = async () => {
let { closeModal, dataSourceFun } = this.props
let { type, dataSource, name, id } = this.state
if (type === '新增') {
if (!name) return message.info('分类名称不可以为空!')
let result = await reqAddCategory(name)
let { status, data, msg } = result
if (status !== 0) {
return message.error(msg, 1)
} else {
message.success('添加分类成功!', 1)
let newDataSource = [...dataSource]
newDataSource.unshift(data)
dataSourceFun(newDataSource)
this.formRef.current.setFieldsValue({ name: undefined }) //给表单设置值
this.formRef.current.resetFields() //清空表单
}
closeModal()
}
if (type === '修改') {
if (!name) return message.info('分类名称不可以为空!')
let result = await reqPutCategory(id, name)
let { status, msg } = result
if (status !== 0) {
return message.error(msg, 1)
} else {
message.success('修改分类成功!', 1)
let newDataSource = [...dataSource]
newDataSource.unshift({ _id: id, name: name })
dataSourceFun(newDataSource)
this.formRef.current.setFieldsValue({ name: undefined }) //给表单设置值
this.formRef.current.resetFields() //清空表单
}
closeModal()
}
}
}