【问题标题】:react-dom: won't accept javascript inside the angular brackets [duplicate]react-dom:不接受尖括号内的javascript [重复]
【发布时间】:2017-09-07 11:30:16
【问题描述】:

由于某种原因,当我尝试将 JavaScript 输入到 HTML 部分的角度部分时,它不起作用。我正在使用 Thymeleaf,并且响应版本 15.0.0

这是 HTML 部分:

   <button className="btn btn-info" onClick={this.displayInfo}>Click for info about {firstName[i]}</button>

所以在这种情况下它不起作用并返回错误:

unexpected error (type=Internal Server Error, status=500) Exception parsing document

如果我删除 onClick={this.displayInfo} 它将起作用。

我的功能:

   displayInfo(){
        console.log("it worked");
    }

The render() function:
    render(){
        var {number, firstName, lastName} = this.state;
        var rows = [];
        for (var i in number)
        {
           rows[i] = (<tr>
                        <td>{number[i]}</td>
                        <td>{firstName[i]}</td>
                        <td>{lastName[i]}</td>
                        <td><button className="btn btn-info" onClick={this.displayInfo}>Click for info about {firstName[i]}</button></td>
                      </tr>);
        }
        var headers = <tr><th>Number</th><th>First Name</th><th>Last Name</th><th>Extra Info</th></tr>;
        return (<table className="table table-bordered">
                                    <thead>{headers}</thead>
                                    <tbody>{rows}</tbody>
                                    </table>);
    }

【问题讨论】:

  • 你确定你没有错别字吗?应该是onClick={this.displayInfo},不带括号
  • 你说得对,我把它改成不加括号了,应该是这样,但还是不行。
  • @Wolfyaskingstuff 你已经提出了类似的问题:stackoverflow.com/questions/46092729/…
  • 我不知道反应,但百里香抛出错误的原因是因为它是无效的 html。 Thymeleaf 希望像这样引用属性:onClick="{this.displayInfo}",所以无论如何你可以让它与 react 一起工作。

标签: reactjs spring-boot thymeleaf react-dom


【解决方案1】:

onClick 处理程序似乎是错误的。

const YourComponent extends Component {
  constructor() {
    this.displayInfo = this.displayInfo.bind(this)
  }

  displayInfo() {
    console.log('do your thing')
  }

  render() {
    return (
      <button
        className="btn btn-info"
        onClick={this.displayInfo}
      >
        Click for info about
      </button>
    )

  }
}

【讨论】:

  • 我从处理程序中删除了括号,但它仍然不起作用。
  • 你在构造函数中也绑定了吗?
  • 是的,我也这样做了。不过,我使用了一个类,而不是 const。
猜你喜欢
  • 2013-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多