reactjs 根据react中动态创建的表单字段的值禁用输入字段

mbzjlibv  于 2023-03-29  发布在  React
关注(0)|答案(1)|浏览(254)

我正在使用antd和react.js创建一个功能来实现动态表单字段,如下面的链接:https://codesandbox.io/s/853qm4?file=/demo.tsx
在这里,我最初希望价格输入字段被禁用,一旦我选择任何视觉值,价格应该自动启用。我已经尝试了onchange和useState,但在这种情况下,所有新添加的字段的价格文本框都被禁用,当我从任何一个字段中选择一个值时,所有字段都被启用。有人能帮助我吗?

g9icjywg

g9icjywg1#

您可以检查是否为特定列表项选择了sight,然后将此输入设置为启用。
form.getFieldValue(['sights', field.name, 'sight'])
这里sights是列表的名称,field.name是列表项的索引。

完整代码

import React from "react";
import "./index.css";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import { Button, Form, Input, Select, Space } from "antd";

const { Option } = Select;

const areas = [
  { label: "Beijing", value: "Beijing" },
  { label: "Shanghai", value: "Shanghai" }
];

const sights = {
  Beijing: ["Tiananmen", "Great Wall"],
  Shanghai: ["Oriental Pearl", "The Bund"]
};

type SightsKeys = keyof typeof sights;

const App: React.FC = () => {
  const [form] = Form.useForm();

  const onFinish = (values: any) => {
    console.log("Received values of form:", values);
  };

  const handleChange = () => {
    form.setFieldsValue({ sights: [] });
  };

  return (
    <Form
      form={form}
      name="dynamic_form_complex"
      onFinish={onFinish}
      style={{ maxWidth: 600 }}
      autoComplete="off"
    >
      <Form.Item
        name="area"
        label="Area"
        rules={[{ required: true, message: "Missing area" }]}
      >
        <Select options={areas} onChange={handleChange} />
      </Form.Item>
      <Form.List name="sights">
        {(fields, { add, remove }) => (
          <>
            {fields.map((field) => (
              <Space key={field.key} align="baseline">
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, curValues) =>
                    prevValues.area !== curValues.area ||
                    prevValues.sights !== curValues.sights
                  }
                >
                  {() => (
                    <Form.Item
                      {...field}
                      label="Sight"
                      name={[field.name, "sight"]}
                      rules={[{ required: true, message: "Missing sight" }]}
                    >
                      <Select
                        disabled={!form.getFieldValue("area")}
                        style={{ width: 130 }}
                      >
                        {(
                          sights[form.getFieldValue("area") as SightsKeys] || []
                        ).map((item) => (
                          <Option key={item} value={item}>
                            {item}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                  )}
                </Form.Item>
                <Form.Item
                  noStyle
                  shouldUpdate={(prev, cur) =>
                    prev?.sights[field?.name]?.sight !==
                    cur?.sights[field?.name]?.sight
                  }
                >
                  {() => {
                    const disabled = !form.getFieldValue([
                      "sights",
                      field.name,
                      "sight"
                    ]);

                    return (
                      <Form.Item
                        {...field}
                        label="Price"
                        name={[field.name, "price"]}
                        rules={[{ required: true, message: "Missing price" }]}
                      >
                        <Input disabled={disabled} />
                      </Form.Item>
                    );
                  }}
                </Form.Item>

                <MinusCircleOutlined onClick={() => remove(field.name)} />
              </Space>
            ))}

            <Form.Item>
              <Button
                type="dashed"
                onClick={() => add()}
                block
                icon={<PlusOutlined />}
              >
                Add sights
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

export default App;

希望这能解决你的问题

相关问题