[英]react on click doesn't work with arrow function
Something is wrong with my code below? 我的以下代码有问题吗? I try to use the arrow function, but nothing happens.
我尝试使用箭头功能,但没有任何反应。
class App extends React.Component {
promt() => {
alert('trigger prompt!');
},
render(){
return(
<h1 onClick="this.promt()">Hello world</h1>
)
}
}
ReactDOM.render(<App />,document.getElementById('app-container'));
https://jsbin.com/nisetupaqa/edit?html,js,console,output https://jsbin.com/nisetupaqa/edit?html,js,控制台,输出
You should pass reference, not result of calling: 您应该传递参考,而不是调用结果:
onClick={this.promt}
It called once, then you have undefined in a handler. 它调用一次,然后在处理程序中未定义。
promt() => {
alert('trigger prompt!');
},
Change to: 改成:
promt() {
alert('trigger prompt!');
}
You haven't to place arrow and comma. 您无需放置箭头和逗号。 Also, you can find it while looking in console on jsbin page.
另外,您可以在jsbin页面上的控制台中查找它。
Full code: 完整代码:
class App extends React.Component {
promt() {
alert('trigger prompt!');
}
render(){
return(
<h1 onClick={this.promt}>Hello world</h1>
)
}
}
ReactDOM.render(<App />,document.getElementById('app-container'));
You've got some incorrect syntax. 您有一些不正确的语法。
promt() => { ... }
is invalid for ES6 classes. promt() => { ... }
对ES6类无效 。 To achieve arrow functions, you must assign it , as a class property, like so: 要实现箭头功能,必须将它分配为类属性,如下所示:
promt = () => {
alert("trigger prompt");
}
Note that class properties are an experiment feature , in stage-2 , which has not been fully implemented. 请注意,类属性是Stage-2中的一项实验功能 ,尚未完全实现。 Per the documentation:
根据文档:
Stage-X (Experimental Presets)
X阶段(实验预设)
Any transforms in stage-x presets are changes to the language that haven't been approved to be part of a release of Javascript (such as ES6/ES2015).
x阶段预设中的任何转换都是对语言的更改,这些更改尚未被批准包含在Javascript版本中(例如ES6 / ES2015)。
“Changes to the language are developed by way of a process which provides guidelines for evolving an addition from an idea to a fully specified feature”
“对语言的更改是通过一个过程开发的,该过程提供了从概念到完全指定的功能的扩展指南”
Subject to change These proposals are subject to change so use with extreme caution, especially for anything pre stage-3.
随时更改这些建议可能随时更改,因此使用时要格外谨慎,尤其是对于第3阶段之前的任何内容。
In the meantime, just use regular ES6 class functions: 同时,只需使用常规的ES6类函数:
promt() {
alert("trigger prompt");
}
Also, no commas between functions. 此外,函数之间没有逗号。 Also, use
{ }
to reference functions as handlers, do not use strings. 另外,使用
{ }
引用函数作为处理程序,不要使用字符串。 That means that this: 这意味着:
<h1 onClick="this.promt()">Hello world</h1>
is incorrect. 是不正确的。 Wrap the reference in curly braces, and remove the parentheses, as you need a function reference , not invocation:
用大括号将引用包裹起来,并删除括号,因为您需要一个函数引用 ,而不是调用:
<h1 onClick={this.promt}>Hello world</h1>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.