首页 > 解决方案 > 语法错误:意外的标记,应为“;”

问题描述

我在反应中收到此语法错误:

3:28:16 PM: Syntax error: Unexpected token, expected ";" (1:10)
3:28:16 PM: > 1 | render() {
3:28:16 PM:     |          ^
3:28:16 PM:   2 |     if (this.props.post) {
3:28:16 PM:   3 |       return (
3:28:16 PM:   4 |         <div className="article">

我已经多次查看每个标签和括号,看看是否都有它们的开始和结束标签/括号,我似乎找不到错误。它可能是别的东西,但我在 javascript 方面还不够好,无法发现错误。

我也不明白错误信息,当它说“预期”时,它到底是什么意思?

这是错误消息引用的代码:

render() {
    if (this.props.post) {
      return (
        <div className="article">
          <a href={"/blog/" + this.props.post.ID} className="blackLink">
            {this.props.post.featured_image ? (
              <img
                className="img-responsive webpic"
                alt="article header"
                src={this.props.post.featured_image}
              />
            ) : (
              ""
            )}
            <h1 className="text-center">{this.props.post.title}</h1>
            <div className="content">{excerpt}</div>
          </a>
          <Link to={"/blog/" + this.props.post.ID}>
            <button className="btn">Read More</button>
          </Link>
        </div>
      );
    } else {
      return null;
    }
  }

标签: javascriptreactjs

解决方案


我想你忘了把函数放在渲染()之前。所以它应该是这样的:

function render() {
    if (this.props.post) {
      return (
        <div className="article">
          <a href={"/blog/" + this.props.post.ID} className="blackLink">
            {this.props.post.featured_image ? (
              <img
                className="img-responsive webpic"
                alt="article header"
                src={this.props.post.featured_image}
              />
            ) : (
              ""
            )}
            <h1 className="text-center">{this.props.post.title}</h1>
            <div className="content">{excerpt}</div>
          </a>
          <Link to={"/blog/" + this.props.post.ID}>
            <button className="btn">Read More</button>
          </Link>
        </div>
      );
    } else {
      return null;
    }
  }

推荐阅读