在ReactJS中使用onClick进行href [英] href with onClick in ReactJS

查看:74
本文介绍了在ReactJS中使用onClick进行href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Reactjs.org处理事件并阻止默认使用以下代码:

As per Reactjs.org to handle event and prevent default use below code:

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

但是,这还需要在构造函数中添加绑定,如:

However, this also requires to add binding in constructor like:

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

我能够通过以下代码获得所需的行为:

I was able to get desired behavior by below code:

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

问题:哪一个更好?似乎第一个需要使用有状态组件,第二个选项可以做任何事情,无论组件是有状态的还是无状态的。

Question: Which one is better option? It seems first one requires to use stateful component and second option can do the things irrespective of component being stateful or stateless.

推荐答案

两者选项产生几乎相同的结果。由于ActionLink是无状态组件,因此将重新创建 handleClick 并重新分配 onClick 。如果你想获得最佳性能,你可以使用类,如下所示:

Both options produce almost the same result. Since ActionLink is a stateless component, handleClick will be re-created and onClick reallocated. If you want to get 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>
    );
  }
}

在此示例中。 handleClick 只绑定一次,只执行render方法。如果您愿意,还可以在构造函数中绑定 handleClick 。但差异很小,我建议你使用你喜欢的那个,你会发现更清楚。

In this example. the handleClick is bound only once and only the render method will be executed. You can also bind the handleClick in the constructor if you prefer. But the differences are so small that I would suggest you to use the one you prefer and you find clearer.

这篇关于在ReactJS中使用onClick进行href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆