简体   繁体   中英

React How to use a child component in a parent component

This works in CodePen (it shows 'Test'):

class Parent extends React.Component {

  render() {
    return ( <h1> Test </h1> ) 
  }
}
/*
 * Render the above component into the div#app
 */
React.render(<Parent />, document.getElementById('app'));

But when I try to encapsulate a Child component, it doesn't (it doesn't show anything).

class Child extends React.Component {

  render() {
    return 
    (
      <div>
        <h1> test </h1>
      </div>
    );
  }
}
class Parent extends React.Component {

  render() {
    return ( <Child /> ) 
  }
}
/*
 * Render the above component into the div#app
 */
React.render(<Parent />, document.getElementById('app'));

Could someone spot what am I doing wrong?

There's nothing wrong with your approach, what bit you is automatic semicolon insertion . In your second example, in the Child component, there's a new line after return , which is interpreted as:

render() {
  return;  // implied semicolon - render returns nothing!
           // following lines are discarded. 
  (
  <div>
    <h1> test </h1>
  </div>
  );
}

So you just need to move the opening paren to be in the same line

class Child extends React.Component {

  render() {
    return (
      <div>
        <h1> test </h1>
      </div>
    );
  }
}

https://jsfiddle.net/69z2wepo/70702/

Just remove new line here

class Child extends React.Component {
render() {
    return (
      <div>
        <h1> test </h1>
      </div>
    );
  }
}

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