DouyinFE / semi-design

🚀A modern, comprehensive, flexible design system and React UI library. 🎨 Provide more than 3000+ Design Tokens, easy to build your design system. Make Semi Design to Any Design. 🧑🏻‍💻 Design to Code in one click
https://semi.design
Other
8.42k stars 711 forks source link

[Form] Form 通过 setValues 给配置了FieldProps initValue但尚不存在的 Field 赋值,特殊情况下不生效 #1848

Open pointhalo opened 1 year ago

pointhalo commented 1 year ago

Is there an existing issue for this?

Which Component

Form

Semi Version

No response

Current Behavior

复现前提:

现状: setValues 给Field( tag )设置的值(‘456’)无效,Field(tag)生效的是 它的initValue '123'

Expected Behavior

setValues 给Field( tag )设置的值(‘456’)后,生效的就是 456,而不是 initValue 123

Steps To Reproduce

  1. 点击 setValues button
  2. 观察form state 数据,有不符合预期的地方如上所述

ReproducibleCode

import React, { useState, useMemo, useEffect, useRef } from "react";
import {
  ArrayField,
  Form,
  Button,
  useFormState,
  TextArea,
  useFormApi
} from "@douyinfe/semi-ui";
import { IconMore } from "@douyinfe/semi-icons";

const ComponentUsingFormState = () => {
  const formState = useFormState();
  return (
    <TextArea style={{ marginTop: 10 }} value={JSON.stringify(formState)} />
  );
};

function QA1() {
  const formRef = useRef(null);

  const setupInitValue = () => {
    let formApi = formRef.current.formApi;
    formApi.setValues(
      {
        isAnchor: "yes",
        tag: "456"
      },
      { isOverride: true }
    );
  };

  return (
    <Form
      ref={formRef}
      style={{ width: 800 }}
      labelPosition="left"
      labelWidth="100px"
      allowEmpty
    >
      {({ formState }) => (
        <Form.Section>
          <Form.RadioGroup field="isAnchor" label="是否主播">
            <Form.Radio value="yes">yes</Form.Radio>
            <Form.Radio value="no">no</Form.Radio>
          </Form.RadioGroup>
          {formState.values.isAnchor === "yes" && (
            <Form.Input
              field={`tag`}
              label="tag"
              style={{ width: "100%" }}
              initValue="123"
            ></Form.Input>
          )}
          <ComponentUsingFormState />
          <Button onClick={() => setupInitValue()}>setValues</Button>
        </Form.Section>
      )}
    </Form>
  );
}

export default QA1;

Anything else?

https://codesandbox.io/s/silent-wave-6zkgvq?file=/src/App.tsx

No response

Jon-Millent commented 1 year ago

看了下代码,是因为setValues的时候,组件因为隐藏状态,没有拿到组件,所以无法设置

image

建议先这么写

    <div style={{display: formState.values.isAnchor === "yes" ?  "none" : "block" }}>
      <Form.Input
              field={`tag`}
              label="tag"
              style={{ width: "100%"}}
            ></Form.Input>
     </div>