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

时间:2016-09-26 19:26:46

标签: javascript reactjs

当用户点击我的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);

1 个答案:

答案 0 :(得分:0)

这应该可以正常工作 -

  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>;
          }
  });