如何处理onClick代码,如果用户点击“在新选项卡中打开链接”;在React js中

How to handle onClick code if user clicks "open link in new tab" in React js

本文关键字:选项 链接 React js 新选项 onClick 处理 何处理 代码 用户 如果      更新时间:2023-09-26

我想运行一些跟踪代码,当用户点击一个按钮在我的react项目。但是,如果用户在新选项卡中打开它,则单击处理程序不会执行。

在React js中有什么解决方案吗?

简单的例子:

var Hello = React.createClass({
    render: function() {
        function click(event) {
            event.preventDefault();
            console.log('You can see me even is user clicked on "open link in new tab"')
        }
        return <div >
            < a href = '#'
        target = "_blank"
        onClick = { click } > Go there < /a> < /div>;
    }
});
React.render( < Hello / > , document.body);

应该没问题-

  const Hello =  React.createClass({
          click(event) {
                    //here this is the component
                    event.preventDefault();
                    console.log('You can see me even is user clicked on "open link in new tab"')
          },
          render() {
           return <div >
                    < a href = '#'
                target = "_blank"
                onClick = { this.click ///or this.click.bind(this) if you want to have this point to the component } > Go there < /a> < /div>;
          }
  });