【问题标题】:Can one React component render by 2 classes?一个 React 组件可以按 2 个类渲染吗?
【发布时间】:2020-08-28 13:45:33
【问题描述】:

一个 React 组件可以用 2 个类渲染吗?就像我在图片中所做的那样。

我尝试了上述方法。它给了我另一个错误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>
);


你们对此有什么想法吗?谢谢

【问题讨论】:

  • 你能提供你用来渲染这个的完整代码吗?如果您使用 map 创建子组件,您可能需要添加 key 属性。文档:reactjs.org/docs/lists-and-keys.html
  • 我只是在我的帖子中添加了我的按钮组件的代码。谢谢。

标签: reactjs components key unique react-props


【解决方案1】:

是的,一个组件可以根据需要多次渲染。问题是您正在映射一个数组并返回一个元素。 React 要求您在这些元素上放置一个唯一的 key 属性,这在理想情况下在渲染之间是一致的。

您可以尝试将您的代码更新为如下所示:

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

【讨论】:

    【解决方案2】:

    我会尽量澄清一点。

    你可以从任何你想要的父组件渲染一个组件。 就您的图片而言,告诉您树中的第一个组件是 App.js,然后 App.js 呈现 Groups.js 组件,Groups.js 呈现您的实际组件。

    在同一页面中,您看到的有关使用“键”的警告是因为您需要为呈现为列表的每个元素设置唯一键值,即重复项。这是因为内部反应工作来比较它是否必须再次重新渲染您的组件需要它。如果您不添加它,您将遇到性能问题(不是一个简单的示例......)。通常你使用你正在渲染的对象的 id。

    我希望我澄清一点。

    【讨论】:

      猜你喜欢
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 2018-01-26
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多