React报错: Uncaught SyntaxError: Unexpected token < in React

 

我创建了一个index.html,就像:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>React Example</title>
        <script crossorigin="anonymous" src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script crossorigin="anonymous" src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
        <script type="text/javascript" src="myScript.js"></script>
    </head>
    <body>
        <div id="root"></div>
        <script type="text/babel">
            ReactDOM.render(<MyTag />, document.getElementById("root"));
        </script>
    </body>
</html>

 

我的react(myScript.js)文件如下所示:

class MyTag extends React.Component {
    render() {
        return <h1>Hello</h1>;
    }
}

 

现在,我尝试运行此代码,这给了我错误,Uncaught SyntaxError:在行的意外标记<return <h1>Hello</h1>;

我该如何解决这个问题?

 

您有两个问题:

1)您要求加载babel!

<script type="text/javascript" src="myScript.js"></script>
#改为
<script type="text/babel" src="/apis/flight-search-box/js/flight-form.js"></script>

 

2)不要 babel 支持的话,可以用浏览器直接解析的方法:

  var CommentForm = React.createClass({
  getInitialState: function() {
      return {author: '', text: ''};

  }, // <---- DON'T FORGET THE COMMA

  render: function() {
      return (
      <form className="commentForm">
          <input type="text" placeholder="Nombre" />
          <input type="text" placeholder="Qué opina" />
          <input type="submit" value="Publicar" />
      </form>
      )
  }
  });

或者

'use strict';

const e = React.createElement;

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  render() {
    if (this.state.liked) {
      return 'You liked this.';
    }

    return e(
      'button',
      { onClick: () => this.setState({ liked: true }) },
      'Like'
    );
  }
}

const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);

 

也就是说,用 React.createClass 或者 React.createElement 代替!

 

本文:React报错: Uncaught SyntaxError: Unexpected token < in React

Leave a Reply