在reactJS中,如何通过按钮按下来调用链接点击?

时间:2016-12-10 21:25:30

标签: reactjs

我有一个按钮。当用户按下它时,我希望结果与用户按下特定链接的结果相同。

换句话说,我想将一个链接表示为一个按钮。

我可以从中看到可以使用Jquery: How to call a href by onclick event of a button?

在ReactJS中执行此操作的“正确”方法是什么?

3 个答案:

答案 0 :(得分:3)

使用React-Router Link代替 Anchor 标记。

import React, { Component } from 'react';
import {Link} from 'react-router-dom'
 // reactClass --
    return (
      <div>
      <Link to='https://react.semantic-ui.com/'>
      <button type="button" className="btn btn-info">Button</button>
      </Link>
      </div>
    );
  // end--

答案 1 :(得分:1)

你甚至不需要jQuery或React来做到这一点。它很简单:

&#13;
&#13;
var employeeProfiles = DL.GetEmployeeProfile(id);

var employeeSelect = JsonConvert.DeserializeObject<List<EmployeeSelection>>(selection);

var result = employeeProfiles.Join(employeeSelect,
    profile => profile.EmployeeId,
    selection => selection.employeeId,
    (x, y) => new EmployeeProfile
    {
        EmployeeId = x.EmployeeId,  
        Block = y.block,
        Edit = y.edit,
        EmployeeName = x.EmployeeName,
        View = y.view
    });
&#13;
var ex = document.getElementById('ex');
ex.onclick = function(){
  console.log('clicked');
}

var bt = document.getElementById('bt');
bt.onclick = function(){
  ex.click();
}
&#13;
&#13;
&#13;

当然,在React中,您可以存储组件的<button id="bt">Click</button> <a id="ex">Triggerable link</a>,绑定到事件,然后触发事件,如下所示:

ref

修改:如果您只想要一个行为类似于链接的按钮,则可以使用此按钮或in this question列出的任何解决方案:

onClick(){
    this.ex.click();
}
render(){
    return (
        <div>
          <button id="bt" onClick={this.onClick.bind(this)} ref={(ref)=>{this.bt = ref}}>Click</button>
          <a id="ex" onClick={()=>console.log("clicked")} ref={(ref)=>{this.ex = ref}}>Triggerable link</a>
        </div>
    )
}

答案 2 :(得分:0)

赞:

<button
    type="button"
    onClick={(e): void => {
      e.preventDefault();
      window.location.href='http://google.com';
      }}
> Click here</button>
相关问题