react.js : javascript in angle brackets not working

对着背影说爱祢 提交于 2019-12-02 14:58:24

问题


For some reason when I try and enter JavaScript into the angle part of the HTML portion it does not work. I'm using Thymeleaf.

Here's the HTML portion:

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

So in this instance it does not work and returns an error:

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

If I remove the onClick={this.displayInfo} it will work.

my function:

   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>);
    }

回答1:


Try this:

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

you should pass an arrow function in your onClick event




回答2:


I was getting the error because Thyemleaf thought that I was typing HTML: I just added this:

  /*<![CDATA[*/
  ...
  /*]]>*/


来源:https://stackoverflow.com/questions/46092729/react-js-javascript-in-angle-brackets-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!