Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

reactjs - how to append react div element from an array with a child element ? and how to give to mapped parent elements unique "key" props

  const group = []
  for (let i = 0; i < 4; i++) {
      group.push(<div className="parent"></div>)
  }

  return (
    <>
      {group.map((item, i) => item )}
    </>
  );
}

here item will be div element with class name "parent", I want to put within it an element, and also I want to give to each item a unique key. (I tried returning from arrow function: <item key={i}> <div className="child"></div> </item> )

question from:https://stackoverflow.com/questions/65929945/how-to-append-react-div-element-from-an-array-with-a-child-element-and-how-to

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For that to work your push should add a function component, which also render children props inside:

  const group = []
  for (let i = 0; i < 4; i++) {
      group.push((props) => <div className="parent">{props.children}</div>)
  }

  return (
    <>
      {group.map((Item, i) => <Item key={i}><div className="child">child {i}</div></Item> )}
    </>
 );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...