简体   繁体   中英

Can one React component render by 2 classes?

Can one React component render by 2 classes? Just like I did in the picture.

在此处输入图像描述

I tried the above. It gives me another error 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".

在此处输入图像描述

The button component Im using in Groups method(Groups.jsx) like this way.

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>
);


Do you guys have any idea about this? Thank you

I will try to clarify a little.

You can render a component from whatever parent component you want. By in the case of your picture, what is telling you that the first component in tree, was App.js, and then App.js rendered Groups.js component, and Groups.js rendered your actual component.

In the same page, the warning you are seeing about using "key" is because you need to set a unique key value for each element that you are rendered as a list, a repeated item. This is because the internal react work to compare if it has to rerender again your component needs it. You will have performance problems (not in an easy example...) if you dont add it. Normally you use the id of the object you are rendering.

I hope i clarified a little.

Yes, a component can be rendered as many times as you would like. The issue is that you are mapping over an array and returning an element. React requires that you put a unique key prop on these elements that ideally are consistent between renders.

You can try to update your code to be something like the following:

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>
);

This is assuming group.name is unique. If you have a unique identifier (eg: group.id ) that would be ideal.

For more examples and why this is necessary you can checkout the official docs: https://reactjs.org/docs/lists-and-keys.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM