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
220 views
in Technique[技术] by (71.8m points)

reactjs - Is it true that the JSX Fragment is just to say, add them to the parents as the last siblings?

If we return in React / JSX:

return (
  <div> ... </div>
  <div> ... </div>
);

It will error out, state it must be a single element, so we can use a React.fragment:

return (
  <>
    <div> ... </div>
    <div> ... </div>
  </>
);

But I noticed these elements are just added to the immediate parent as children, or if the parent already has some children, then these elements are added as the "later" siblings of the existing children.

Is this how it works? Basically it just add them as siblings of the parent node.

question from:https://stackoverflow.com/questions/66048248/is-it-true-that-the-jsx-fragment-is-just-to-say-add-them-to-the-parents-as-the

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

1 Answer

0 votes
by (71.8m points)

React.Fragment only groups elements without adding an extra node to the DOM.

But I noticed these elements are just added to the immediate parent as children, or if the parent already has some children, then these elements are added as the "later" siblings of the existing children.

Its the developer's decision on where the element will render, a counterexample:

<div>
  <>
    <div>Hello</div>
    <div>World</div>
  </>
  <div>Other</div>
</div>

// Results
<div>
  <div>Hello</div>
  <div>World</div>
  <div>Other</div>
</div>

Or as components:

const App = () => {
  return (
    <div>
      <ComponentUsingFragment />
      <div>Other</div>
    </div>
  );
};

const ComponentUsingFragment = () => {
  return (
    <>
      <div>Hello</div>
      <div>World</div>
    </>
  );
}

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

...