簡體   English   中英

從條件語句渲染多個 React 組件

[英]Render multiple React components from conditional statements

我有一個definition對象,根據每個表單的“類型”,我呈現一個特定的組件。 例如:

const definition = 
{
name: "test", 
id: 1,
form: [
  {type: "text"}, 
  {type: "checkbox"}, 
  {type: "radio"}]
};

所以要訪問表單類型,我只是做了一個簡單的地圖:

const definitionTypes = definitions.form.map ( form => form.type )

我現在有一個存儲在definitionTypes上的所有表單類型條目的數組,並且我有三個組件需要根據該 definitionTypes 數組中的關鍵字進行呈現。 所以對於“文本”,我有一個名為<DefinitionText />的組件,我導入了它,等等。

我遇到問題的地方是根據 definitionTypes 數組中的類型找出返回多個組件的解決方案。 最終目標是讓這 3 個組件從該數組呈現:

  // if definitionTypes includes "text" then render...
  <DefinitionText />

  // also if definitionTypes includes "checkbox" then render...
  <DefinitionCheckbox />

  // also if definitionTypes includes "radio" then render...
  <DefinitionRadio />

我嘗試使用if/else語句將每個組件推送到results變量,然后呈現該變量,但results變量發回錯誤。 任何幫助根據條件渲染多個組件都將是一個巨大的幫助!

有了那個defintionTypes數組,剩下的就應該有點簡單了……例如,您可以使用 switch 語句。 查看片段。

 function Radio(){ return <input type='radio'></input> } function Text(){ return <input type='text'></input> } function CheckBox(){ return <input type='checkBox'></input> } function App(){ const definitionTypes = ['text', 'checkBox', 'radio'] return <div> {definitionTypes.map(type => { switch(type){ case 'text': return <Text/> break case 'radio': return <Radio/> break case 'checkBox': return <CheckBox/> break default: break }})} </div> } ReactDOM.render(<App/>, document.getElementById('root'))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script> <div id='root'></div>

首先構建組件的對象映射:

const Components = {
  foo: Foo,
  bar: Bar
};

然后使用密鑰名稱的字符串訪問:

const DynamicComponent = Components[componentName];

<DynamicComponent />

在組件中使用地圖的快速示例

{definitions.form.map( form => {
  const DynamicComponent = Components[form.type];
  return <DynamicComponent />
})}

暫無
暫無

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

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