如何在 React class 上定义事件处理程序?
How to define eventhandler on React class?
我刚开始使用 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
您需要这样包装 onClick:
return <div><p>{message}</p><button onClick={function() {console.log("hi")}}>hier</button></div>;
就目前而言,onClick=function(){}
不会将该函数转换为 JSX 表达式。
Fiddle:
https://jsfiddle.net/gwm6dd4n/
React 的 JSX 语法只是语法糖,可以转换为常规 JS。任何时候你想将常规 JS 注入其中,你都需要围绕它使用波浪形。代码中的事件处理程序定义缺少周围的 {}。我可以推荐更简洁的 lambda 表达式吗...使用
onclick={()=> console.log("hi")}
我刚开始使用 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
您需要这样包装 onClick:
return <div><p>{message}</p><button onClick={function() {console.log("hi")}}>hier</button></div>;
就目前而言,onClick=function(){}
不会将该函数转换为 JSX 表达式。
Fiddle: https://jsfiddle.net/gwm6dd4n/
React 的 JSX 语法只是语法糖,可以转换为常规 JS。任何时候你想将常规 JS 注入其中,你都需要围绕它使用波浪形。代码中的事件处理程序定义缺少周围的 {}。我可以推荐更简洁的 lambda 表达式吗...使用
onclick={()=> console.log("hi")}