簡體   English   中英

根據 React 中的選定選項呈現表單字段

[英]Render form fields based on selected option in React

我想實現一個由基本字段(例如:產品名稱、價格和類型)組成的表單,然后是特定於類型的字段,具體取決於所選類型。

起初,該解決方案似乎很簡單( 請參閱此代碼框),因為我設法根據當前product state 中找到的類型來渲染不同的組件。

但是,由於這些組件是在內部使用諸如useEffect之類的鈎子時有條件地呈現的,所以當我從一種產品類型更改為另一種產品類型時,它們違反了鈎子規則並導致以下錯誤:

Should have a queue. This is likely a bug in React. Please file an issue.

Warning: React has detected a change in the order of Hooks called by TypeSpecificForm. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks (...)

   Previous render            Next render
   ------------------------------------------------------
1. useState                   useEffect
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    in TypeSpecificForm (at ProductForm.js:36)
    in div (at ProductForm.js:14)
    in ProductForm (at App.js:8)
    in App (at index.js:15)
    in StrictMode (at index.js:14)

在此處輸入圖像描述

動態呈現這些部分字段的正確方法是什么?

正如我所懷疑的那樣,解決方案相當愚蠢。

而不是為動態字段返回渲染 function ...

function TypeSpecificForm({ product, onChange }) {
  const productType = productTypes[product.type];
  if (!productType?.renderForm) return null;

  return productType.renderForm({ product, onChange });
}

...我將其稱為 React Node 組件,如下所示:

function TypeSpecificForm({ product, onChange }) {
  const productType = productTypes[product.type];
  if (!productType?.renderForm) return null;
  const Component = productType.renderForm

  return <Component product={product} onChange={onChange} />
}

現在 React 不再抱怨違反 Hooks 規則,一切都按預期工作。

然而,我記得在 React 文檔中看到這兩種方法可以互換,但顯然它們不是。 一旦找到此問題的確切根本原因,我將更新我的答案。

編輯:我仍然無法在官方文檔上找到任何強調通過渲染 function 與 JSX 組件渲染組件之間的差異的內容,但我確實遇到了關於這個主題的有趣討論

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM