Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Return multiple elements inside React.render()

I am new in react and I encountered with this problem:

render: function(){
    return (
        <h3>Account</h3>
        <a href="#" onClick={some_event}>Login</a>
        <a href="#" onClick={some_event}>Logout</a>
)}

When I am rendering like this it gives me error saying like multiple components must wrapt with end

Should I make one componenet for each html tag or each line or I can render in that way..

Any suggestion ?

question from:https://stackoverflow.com/questions/34893506/return-multiple-elements-inside-react-render

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

1 Reply

0 votes
by (71.8m points)

In React < v16.0 the render method can only render a single root node. (update: this is changed in v16, see below). In your case, you're returning 3 nodes. To get around this you can wrap your 3 nodes in a single root node:

render: function(){
  return (
    <div>
      <h3>Account</h3>
      <a href="#" onClick={some_event}>Login</a>
      <a href="#" onClick={some_event}>Logout</a>
    </div>
)}

In React v16 it's possible for render() to return an array of elements.

Like with other arrays, you’ll need to add a key to each element to avoid the key warning:

render() {
  return [
    <ChildA key="key1" />,
    <ChildB key="key2" />,
    <ChildC key="key3" />,
  ];
}

Another option is to use a Fragment. Fragments let you group a list of children without adding extra nodes to the DOM.

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

There is also a short syntax (<>) for declaring fragments:

render() {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...