导航到其他页面之前如何执行onclick?

时间:2019-04-22 17:18:40

标签: javascript reactjs onclick

我在React中工作,并且遇到以下情况。

import numpy as np

def sum_of_prods_of_pairs(M):
    # note: this function performs slightly better if given booleans
    # e.g. M = np.random.choice([True, False], (len_strings, n_strings))
    n_strings, len_strings = M.shape
    MT = M.T
    M_sum = np.zeros((len_strings, len_strings))

    for i in range(len_strings):
        M_sum[i, i+1:len_strings] = np.sum(np.multiply(MT[i], MT[i+1:len_strings]), axis=1)
    M_sum += M_sum.T
    return M_sum

# n_strings = 150
# len_strings = 10000

# np.random.seed(91)
# C = np.random.choice([True, False], (n_strings, len_strings))
# C = np.random.binomial(1, 0.1, (n_strings, len_strings))
C = np.array([[1,0,1], [1,1,0], [1,1,1]])

ordered_sum_matrix = sum_of_prods_of_pairs(C)

print(ordered_sum_matrix)

现在,我希望在单击链接之前执行onclick。但是,我看不到它的发生。

如何解决此问题?谢谢。

4 个答案:

答案 0 :(得分:0)

请注意,onclick()将在页面重定向之前触发。似乎您可能想在onclick函数中处理导航,而不是拥有href属性。通过这种方式,您可以有条件地重定向(如果需要)和/或等待一些异步代码完成。

onClick = url => {
  alert('Do something');
  window.location.href = url;
}
<a href='#' onclick="onClick('https://stackoverflow.com')">here.</a>

反应性片段:

class App extends React.Component {
  onClickDoSomething = link => ev => {
    alert(link);
    // Do any operations here
    window.location.href = link;
  }
  render() {
    const link = 'https://stackoverflow.com';
    return <div>
      <a href='#' onClick={this.onClickDoSomething(link)}>here.</a> 
    </div>;
  }
}

ReactDOM.render( <App/> , document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id='app'></div>

答案 1 :(得分:0)

您的点击处理程序应该是这样

onClickDoSomething=(link)=>{
//do something,then redirect to given link
window.location.href=link

}

,您应该将链接呈现为

<a  variant="primary" onClick={()=>{this.onClickDoSomething(link)}}>
                      here.
</a>

答案 2 :(得分:0)

首先会建议使用react路由器 但是如果链接是外部的,则另一种方法是保持href =“#”并在最后编写onclickHandler函数,只需使用onclickHandler window.location = [链接]

您要访问的

希望有帮助

答案 3 :(得分:-1)

您可以使用mouseenter事件,当您将鼠标悬停在链接上时会触发该事件。这意味着它将在click事件之前被触发

相关问题