简体   繁体   English

在 ReactJS 中使用 onClick href

[英]href with onClick in ReactJS

As per Reactjs.org to handle event and prevent default use below code:根据 Reactjs.org 处理事件并防止默认使用以下代码:

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 behaviour 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.似乎第一个需要使用有状态组件,第二个选项可以做这些事情,而不管组件是有状态的还是无状态的。

Both options produce almost the same result.这两个选项产生几乎相同的结果。 Since ActionLink is a stateless component, handleClick will be re-created and onClick reallocated.由于 ActionLink 是一个无状态组件, handleClick将被重新创建并重新分配onClick 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={this.handleClick}>
        Click me
      </a>
    );
  }
}

In this example.在这个例子中。 the handleClick is bound only once, and only the render method will be executed. handleClick只绑定一次,并且只执行 render 方法。 You can also bind the handleClick in the constructor if you prefer.如果您愿意,也可以在构造函数中绑定handleClick But the differences are so small that I would suggest you use the one you prefer and you find it clearer.但是差异如此之小,我建议您使用您喜欢的那个,并且您会发现它更清晰。

在页面加载时修复此重复函数调用的最佳方法是

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

There is a slight performance issue with ---the second--- both snippets. ---第二个---两个片段存在轻微的性能问题。 Every time you render that <a> tag the function in the onClick will be reallocated.每次渲染<a>标签时, onClick的函数都会被重新分配。

Here is a detailed post outlining all the ways to bind this in react.这是一篇详细的文章,概述了在 react 中绑定this所有方法。 ( https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.53op90a6w ) ( https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.53op90a6w )


Edited.已编辑。 I misinterpreted the example code, it has the same issue of allocating the function on each render as the inline arrow function snippet.我误解了示例代码,它在每个渲染上分配函数的问题与内联箭头函数片段相同。 Refer Vincent D'amour 's accepted answer.参考Vincent D'amour接受的答案。

就我而言,如果我有href="#"无论如何我都会被重定向,所以我像这样离开了我的链接/按钮:

<a href="" role="button" onClick={this.myAction}>Click here</a>

I think you should bind with current object.我认为你应该绑定当前对象。 let it try.让它试试。 refer the following example:请参考以下示例:

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

using this code will produce a warning使用此代码将产生警告

<a href="#" onClick={() => action()}>Link</a>

there is a workaround this by following react cli advice and it is that if you cannot provide a valid link address with HTTP: etc to change your tag to a button.通过遵循 react cli 建议可以解决此问题,如果您无法通过 HTTP: etc 提供有效的链接地址,请将您的标签更改为按钮。 It is possible to make a button look like a link with pure CSS.可以使用纯 CSS 使按钮看起来像链接。 here is the example.这是示例。

step one create the button styles第一步创建按钮样式

const buttonToLink = {
        fontSize: '1em',
        textAlign: 'left',
        color: 'blue',
        background: 'none',
        margin: 0,
        padding: 0,
        border: 'none',
        cursor: 'pointer'
     
    }

step 2 add the styles to the button第 2 步将样式添加到按钮

<button style={buttonToLink} onClick={() => action()}> This link has no warning</button>

Please note that "action()" is the function we want the button to follow.请注意“action()”是我们希望按钮跟随的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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