2016-02-05 54 views
0

我剛開始接觸ReactJS,我試圖觸發按鈕上的onCLick事件:如何在React類上定義事件處理程序?

/** 
* @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 

回答

0

你需要換行的onClick這樣:

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

因爲它的立場,onClick=function(){},並不意味着功能爲JSX表達。

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

0

陣營的JSX語法只是語法糖,其被轉換成普通JS。任何時候你想要在其中注入普通的JS,你都需要使用它。代碼中的事件處理程序定義缺少周圍的{}。我可以推薦更簡潔的lambda表達式來代替...使用

onclick={()=> console.log("hi")}