简体   繁体   中英

React - Uncaught Invariant Violation:

When I run my code on browser, I'm getting this error message.

Uncaught Invariant Violation: MyComponent.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

I'm using Atom as my code editor and running on a chrome web server. Here is my code.

<body>
<div id="react-comp"></div>
  <script type="text/babel">
    var MyComponent = React.createClass({
      render: function() {
        return
          <div>
            <h1>{this.props.text}</h1>

          </div>;
      }
    });

    ReactDOM.render(
      <div>
        <MyComponent text="Hello World"/>
        <MyComponent text="Hello"/>
      </div>  
    , document.getElementById('react-comp'));


  </script>
</body>

It might be a jsx transforming issue? or any other thing?

You are likely hitting JavaScripts automatic semicolon insertion after return . Just remove the line break before your div.

var MyComponent = React.createClass({
  render: function() {
    return <div> // Change this line
        <h1>{this.props.text}</h1>

      </div>;
  }
});

Just change your render function to

var MyComponent = React.createClass({
  render: function() {
    return (
      <div>
        <h1>{this.props.text}</h1>    
      </div>
    );
  }
});

Daniel's suggestion is also correct.

I don't know which version of React you are using, as I know some old version makes error if the JSX syntax isn't wrapped with (). Try to do this on MyComponent's render method:

render: function() {
    return (
      <div>
        <h1>{this.props.text}</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