antd Modal + Form搭配使用 / Ant Design 4.x的Modal中表单验证

最近写React + antd时,使用到Modal和Form组件时候,因为Modal组件自带onOk按钮,因此不能使用Form自带的onFinished函数,所以一直不清楚怎么能自己发起对表单的校验。看完官网和这位博主的代码后,大致了解可以通过使用 ref 的方式获得表单值甚至可以发起表单校验方法。
代码如下

export default class Role extends Component {

  // 校验
  validateRole = () => {
    this.formRef.current.validateFields()
      .then(values => {
        this.addRole(values)
        this.formRef.current.validateFields()
      })
      .catch(info => {
        let error = info.errorFields
        console.log(error);
        error.forEach(item => {
          message.error(item.errors)
        })
      });

  }

// 发起请求
  addRole = async (values) => {
    const { data: result } = await reqRoleAdd(values.roleName)
    this.setState({ isShowAdd: false })
    if (result.status === 0) {
      message.success('添加角色成功')
    } else {
      message.error('添加角色失败')
    }
    this.getRoles()
  }

  formRef = React.createRef(); //关键代码

  render() {
    const { roles, role, isShowAdd } = this.state

    const title = (
      <span>
        <Button type="primary" onClick={() => this.setState({ isShowAdd: true })}>创建角色</Button>
        <Button type="primary" disabled={!role._id} style={{ marginLeft: 15 }}>设置角色权限</Button>
      </span>
    )

    return (
      <Card title={title}>
        <Modal title="添加角色" visible={isShowAdd === true} onOk={this.validateRole} onCancel={() => { this.setState({ isShowAdd: false }) }}>
          <Form ref={this.formRef}> //关键代码
            <Form.Item
              label="角色名称"
              name="roleName"
              rules={[{ required: true, whitespace: true, message: '角色名称必须输入' }]}
            >
              <Input></Input>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    )
  }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值