如何在一个类组件reactjs中使用modal和antd来使用form?Form.useForm()和Form.create()在这些方法上有问题

cld4siwp  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(284)

我试图创建一个窗体使用模态,不能使用Form.useForm(),因为它是一个类,它抛出无效的钩子调用错误。
我可以用什么来替代Form.useForm(),我也尝试过使用Form.create(),但它被弃用了。

import React from "react";
import { inject, observer } from "mobx-react";
import { LoginOutlined  } from "@ant-design/icons";
import { Input, Button, Modal, Tooltip, message, Form } from "antd";
import * as mobx from "mobx";
import "./index.less";

@inject("store")
@observer
class AddNewEntry extends React.Component {
  constructor(props) {
    super(props);
  }

  state = {
    showModal: false,
    firstName: "",
    middleName: "",
    lastName: ""
  };

  render() {
    const { showModal, firstName, middleName, lastName } = this.state; 
    const [form] = Form.useForm(); 

    const handleNewEntry = () => {
      this.setState({ showModal: true })
    }

    const handlefirstName = (e) => {
      this.setState({ firstName: e.target.value });
    };

    const handlemiddleName = (e) => {
      this.setState({ middleName: e.target.value });
    };

    const handlelastName = (e) => {
      this.setState({ lastName: e.target.value });
    };

    const handleCancel = () => {
      this.setState({ showModal: false })
    };

    const handleOk = () => {
      var firstNameId = "";
      var middleNameId = "";
      var lastNameId = "";
      if (firstName != "" && middleName != "" && lastName != "") {
        if (firstName != "") {
          const prefix = "n";
          const incrementNum = "01" + 1;
          firstNameId = prefix + incrementNum;
        }
        if (middleName != "") {  
          middleNameId = firstNameId + "01";
        }
        if (lastName != "") {
          lastNameId = middleNameId + "02";
        }
        this.props.store.addNewEntry(firstNameId, firstName, { middleNameId: middleNameId, middleName: middleName, lastNameId: lastNameId, lastName: lastName });
        this.setState({ showModal: false });
      } else {
        message.warning("Please Enter All Names!")
        this.setState({ showModal: true });
      }
    };

    return (
      <>
        <Tooltip placement="top" title="Add New Entry">
          <Button
            icon={<LoginOutlined />}
            size={"small"}
            disabled={this.props.disable}
            onClick={handleNewEntry}> New Entry </Button>
        </Tooltip>
        <Modal
          title="Enter Name you want"
          visible={showModal}
          // onOk={handleOk}
          // onCancel={handleCancel}
          zIndex={10}
          className="modalWidth"
          footer={[
            <><Button onClick={handleCancel}>
              Cancel
            </Button>
              <Button htmlType="submit" form={form} type="primary" onClick={handleOk}>
                Ok
              </Button></>
          ]}
        >
          <Form
            form={form}
            labelCol={{ span: 6 }}
          >
            <Form.Item
              style={{ marginBottom: "4px" }}
              label="First Name"
              name="First Name"
              rules={[{ required: true, message: 'First name is required!' },
              {
                pattern: new RegExp(/^[a-zA-Z0-9_.-]*$/),
                message: "field does not accept special characters"
              }]}
            >
              <Input
                placeholder="Enter First Name"
                value={firstName}
                onChange={handlefirstName}
                className="inputWidth"
              />
            </Form.Item>
            <Form.Item
              style={{ marginBottom: "4px" }}
              label="Middle Name"
              name="Middle Name"
              rules={[{ required: true, message: 'Middle name is required!' },
              {
                pattern: new RegExp(/^[a-zA-Z0-9_.-]*$/),
                message: "field does not accept special characters"
              }]}
            >
              <Input
                placeholder="Enter Middle Name"
                value={middleName}
                onChange={handlemiddleName}
                className="inputWidth"
              />
            </Form.Item>
            <Form.Item
              style={{ marginBottom: "4px" }}
              label="Last Name"
              name="Last Name"
              rules={[{ required: true, message: 'Last name is required!' },
              {
                pattern: new RegExp(/^[a-zA-Z0-9_.-]*$/),
                message: "field does not accept special characters"
              }]}
            >
              <Input
                placeholder="Enter Last Name"
                value={lastName}
                onChange={handlelastName}
                className="inputWidth"
              />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  }
}

export default AddNewEntry;

有人能帮我解决这个问题吗?我怎样才能在类组件中创建表单
出现以下错误:

bundle.js:83800 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at Object.throwInvalidHookError (bundle.js:83800:9)
    at Object.useRef (bundle.js:101179:21)
    at useForm (bundle.js:45598:52)
    at Object.useForm (bundle.js:8392:74)
    at AddNewEntry.render (bundle.js:17285:65)
    at allowStateChanges (bundle.js:35506:12)
    at bundle.js:33637:77
    at trackDerivedFunction (bundle.js:36121:18)
    at Reaction.track (bundle.js:36707:18)
    at AddNewEntry.reactiveRender [as render] (bundle.js:33633:14)

此外,我需要删除单击确定按钮的表单字段。

k4ymrczo

k4ymrczo1#

参考下面的例子,它在我的情况下工作,只是分享,如果它帮助别人:)
Antd clear form after submit in reactjs

相关问题