简体   繁体   中英

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

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.

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. 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. Per the documentation:

Stage-X (Experimental Presets)

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).

“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.

In the meantime, just use regular ES6 class functions:

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> 

Here's a fiddle that is working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM