Href with onClick in ReactJS

According to Reactjs.org to handle event and prevent default usage for below code:

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }
  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}
      

Run codeHide result


However, this also requires adding a binding in the constructor, for example:

this.handleClick = this.handleClick.bind(this);

      

I managed to get the desired behavior with below code:

<span>
<a href="#" 
onClick={()=>doSomething(arg1,agr2)}>Click here</a></span>
      

Run codeHide result


Question: Which option is better? It seems that the first is to use a stateful component, and the second option can do things regardless of whether the component is stateful or inactive.

+3


source to share


3 answers


Both options give almost the same result. Since ActionLink is a stateless component handleClick

will be recreated and onClick

redistributed. If you want the best performance, you can use a class, something like this:

class ActionLink extends React.Component () {
  handleClick = (e) => {
    e.preventDefault();
    console.log('The link was clicked.');
  };

  render() {
    return (
      <a href="#" onClick={handleClick}>
        Click me
      </a>
    );
  }
}

      



In this example. handleClick

is bound only once and only the render method will be executed. You can also bind handleClick

in the constructor if you like. But the differences are so small that I suggest you use the one that you prefer and you will find it clearer.

+7


source


There is a little performance issue: --- the second is both snippets. Every time you show a tag <a>

, the function in onClick

will be redistributed.

Here is a detailed post that outlines all the ways to bind this

to react. ( https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.53op90a6w )




Ed. I misinterpreted the example code, it has the same problem of allocating a function for each render as an inline snippet. Contact Vincent D'amour who accepted the answer.

+1


source


the best way to fix this repeated function call on page load is to do

<a href="#" onClick={() => {this.handleClick}}>click me</a>

      

0


source







All Articles