如何在React类上定义eventhandler?

时间:2016-02-05 02:42:27

标签: javascript react-jsx

我刚开始使用ReactJS,我试图在按钮上触发onCLick事件:

/**
 * @jsx React.DOM
 */
var ExampleApplication = React.createClass({
    render: function () {

        var message ='Joko';

        return <div><p>{message}</p><button onClick=function() {console.log("hi")}>hier</button></div>;
    }
});

React.renderComponent(
    <ExampleApplication />,
    document.getElementById('container')
);

如何显示console.log消息并触发onClick事件?我得到的错误是:

Uncaught Error: Parse Error: Line 9: XJS value should be either an expression or a quoted XJS text
    at http://localhost:63343/react-0.11.2/examples/basic-jsx-external/example.js:9:53

2 个答案:

答案 0 :(得分:0)

你需要将onClick包装起来:

return <div><p>{message}</p><button onClick={function() {console.log("hi")}}>hier</button></div>;

目前,onClick=function(){}不会将该函数转换为JSX表达式。

小提琴: https://jsfiddle.net/gwm6dd4n/

答案 1 :(得分:0)

React的JSX语法只是语法糖,可以转换为常规JS。无论何时你想要将常规JS注入其中,你都需要使用波浪形。代码中的事件处理程序定义缺少周围的{}。我可以推荐更简洁的lambda表达式......使用

onclick={()=> console.log("hi")}
相关问题