Skip to content

🧐[问题] 自定义表单项中如何获取阅读态 #7750

Open
@africa1207

Description

@africa1207

🧐 问题描述

目前自定义一个表单项,获取不到是否是readonly,手动添加readonly到组件上,但是如何获取到value 的值来分别渲染?
在customInput.tsx中直接获取不到value和readonly,文档中写自定义表单项遵循

  • 提供受控属性 value 或其它与 valuePropName 的值同名的属性。
  • 提供 onChange 事件或 trigger 的值同名的事件。
    就算我手动在调用<CustomInput readonly={readonly}>获取到readonly了,也没法获取到value,使用了Form.useForm,提示Instance created by useFormis not connected to any Form element. Forget to passform prop?

💻 示例代码

index.tsx

import {
  ProForm,
  ProFormText,
  ProFormInstance
} from "@ant-design/pro-components";
import { Switch } from "antd";
import React, { useRef, useState } from "react";
import CustomInput from "./CustomInput";

export default function () {
  const [readonly, setReadonly] = useState(false);
  const formRef = useRef<ProFormInstance>();
  function setValue() {
    formRef.current?.setFieldsValue({
      username: "abc",
      customInput: "def"
    });
  }

  return (
    <div>
      <button onClick={setValue}>click</button>
      <Switch
        style={{
          marginBlockEnd: 16
        }}
        checked={readonly}
        checkedChildren="编辑"
        unCheckedChildren="只读"
        onChange={setReadonly}
      />
      ;
      <ProForm
        formRef={formRef}
        readonly={readonly}
        onFinish={async (values) => {
          console.log(values);
        }}>
        <ProFormText name="username" label="姓名" />
        <CustomInput name="customInput" label="自定义" />
      </ProForm>
    </div>
  );
}

customInput.tsx

import { Input, Form } from "antd";
import { useMemo } from "react";

export default function (props) {
  const { value = "", onChange, readonly, ...rest } = props;
  console.log("props:", props);
  const form = Form.useForm();
  const _value = useMemo(() => form[0].getFieldValue(props.name), [value]);

  return readonly ? (
    <Form.Item {...rest}>
      <div>{_value}</div>
    </Form.Item>
  ) : (
    <Form.Item {...rest}>
      <Input value={value} onChange={onChange} {...rest} />
    </Form.Item>
  );
}


🚑 其他信息

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions