簡體   English   中英

一個 React 組件可以按 2 個類渲染嗎?

[英]Can one React component render by 2 classes?

一個 React 組件可以按 2 個類渲染嗎? 就像我在圖片中所做的那樣。

在此處輸入圖像描述

我試過上面的。 它給了我另一個錯誤Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of "Groups". Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of "Groups".

在此處輸入圖像描述

我在 Groups 方法(Groups.jsx)中使用的按鈕組件就是這樣。

const Groups = (props) => (
  <div className = 'panel'>
    <h2>Groups</h2>


    <button >Get Groups</button>


    <div className = 'group-list'>
      {props.groups.map((group) =>
        <GroupsEntry name = {group.name}
          members = {group.members}/>
      )}
    </div>
  </div>
);


你們對此有什么想法嗎? 謝謝

我會嘗試澄清一點。

你可以從任何你想要的父組件渲染一個組件。 就您的圖片而言,告訴您樹中的第一個組件是 App.js,然后 App.js 呈現 Groups.js 組件,而 Groups.js 呈現您的實際組件。

在同一頁面中,您看到的有關使用“鍵”的警告是因為您需要為呈現為列表的每個元素設置唯一鍵值,即重復項。 這是因為內部反應工作來比較它是否必須再次重新渲染您的組件需要它。 如果您不添加它,您將遇到性能問題(不是一個簡單的示例......)。 通常你使用你正在渲染的 object 的 id。

我希望我澄清一點。

是的,一個組件可以渲染任意多次。 問題是您正在映射一個數組並返回一個元素。 React 要求您在這些元素上放置一個唯一的key prop,理想情況下,這些元素在渲染之間是一致的。

您可以嘗試將代碼更新為如下所示:

const Groups = props => (
  <div className="panel">
    <h2>Groups</h2>

    <button>Get Groups</button>

    <div className="group-list">
      {props.groups.map(group => (
        <GroupsEntry key={group.name} name={group.name} members={group.members} />
      ))}
    </div>
  </div>
);

這是假設group.name是唯一的。 如果您有一個唯一標識符(例如: group.id ),那將是理想的。

有關更多示例以及為什么需要這樣做,您可以查看官方文檔: https://reactjs.org/docs/lists-and-keys.html

暫無
暫無

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

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