【问题标题】:useRef only gets last values from mapped form antd ReactjsuseRef 仅从映射形式 antd Reactjs 获取最后一个值
【发布时间】:2022-12-30 00:12:18
【问题描述】:

我从一个 API 得到一堆引用,我想插入每个引用及其数量,我使用的是 antd 形式的 useRef 我得到未定义的值

const formRef =useRef();

const  submitFunction= (values) => {
    
    formRef.current.validateFields().then((values) => {
 
      console.log("Values:", values);
    });

  };

{reference.map((e, index) => (
        <Form  ref={formRef} 
        initialValues={{
          ["Ref"]: e.reference 
        }}>
          <div>
            <Row style={{ backgroundColor: "darkcyan" }} gutter={8}>
              <Col span={5}>
                <Form.Item   label="Ref" name="Ref" labelCol={{ span: 6 }}>
                  <Input   key={index} defaultValue={e.reference}  />
                </Form.Item>
              </Col>

              <Col span={8}>
                <Form.Item name="quantity">
                  <InputNumber key={index} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item>
                  <Button onClick={() => submitFunction()}>
                    click me
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </div>
        </Form>
      ))}

参考文献列表

【问题讨论】:

    标签: reactjs api input antd use-ref


    【解决方案1】:

    也许现在回答这个问题为时已晚。似乎因为您有一个Form组件列表并且formRef连接到每个表单,逻辑上表单的参考值在formRef中被一个一个地替换,直到到达最后一个。如果你想防止这种情况发生,你可以将 formRef 初始化为一个空数组,如下所示:

    const formRef = useRef([]);
    

    并像这样定义 Form 组件的 ref 属性:

    ref={el => {
       if (el)  formRef.current[index] = el
    }}
    

    最后更改submitFunction

    const submitFunction = (value) => {
      formRef.current.map(form => {
        form.validateFields().then((values) => {
          console.log("Values:", values);
        });
      })
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2022-01-15
      • 2023-03-07
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      相关资源
      最近更新 更多