【问题标题】:useRef in <Form /> Component | Informed | PWA Studio | React<Form /> 组件中的 useRef |知情 | PWA 工作室 |反应
【发布时间】:2022-07-15 23:27:20
【问题描述】:

我需要使用 useRef() 执行表单提交。我正在尝试引用“informed”(PWA Studio 表单库)提供的组件,但该引用不起作用。该引用不适用于通知 Form,但我不知道为什么。我使用普通的 html 表单 &lt;form ref={formRef}&gt;... 尝试了相同的引用,并且在这种情况下有效。

const formRef = useRef(null);
...
// 'informed Form'
<Form ref={formRef}>...</Form>

// It does't submit the form after function executed
const handleSubmit = () => {
  formRef.current && formRef.current.submit();
};

【问题讨论】:

    标签: reactjs magento2 use-ref pwa-studio


    【解决方案1】:

    Informed 中确实不可能通过简单的 useRef 方式来引用它。为了实现您的目标,您可以在表单组件中使用 getApi={formRef.current} 属性

    // You can create your useRef() in this way
    const formApiRef = useRef(null);
    const setFormApi = useCallback(api => (formApiRef.current = api), []);
    
    // In your form component set the apiForm
    <Form getApi={setFormApi}> ... </Form>
    
    // In your handleSubmit function in order to submit you can do this
    const handleSubmit = useCallback(() => {
        const { current: formApi } = formApiRef;
    
        if (formApi) {
          formApi.submitForm();
        }
      }, [applyCoupon, cartId]);
    

    【讨论】:

      猜你喜欢
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 2021-08-28
      • 2020-06-20
      • 2021-06-09
      • 1970-01-01
      相关资源
      最近更新 更多