如何在 Link: ReactJS 上使用 onClick 事件? [英] How to use onClick event on Link: ReactJS?

查看:119
本文介绍了如何在 Link: ReactJS 上使用 onClick 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React 路由器中,我有 toonClick 属性,如下所示

In React router, I have to and onClick attributes as shown below

<li key={i}><Link to="/about" onClick={() => props.selectName(name)}>{name}</Link></li>

state = {
    selectedName: ''
};

selectName = (name) => {
   setTimeout(function(){this.setState({selectedName:name});}.bind(this),1000);
   // this.setState({selectedName: name});
}

  • to 属性导航到 about Route
  • onClick 为状态变量 selectedName 赋值,该变量将在导航到关于"页面时显示.
  • 当我在点击时调用 timeout insided 函数时,它会导航到新页面,一段时间后状态会更新,导致显示以前的名称,直到状态用新名称更新.

    When I give timeout insided function called on click, its navigating to new page and after sometime state is getting updated resulting in displaying previous name until state is updated with new name.

    有没有办法让onClick函数中的代码被执行后才导航到新路由.

    Is there a way where it will navigate to the new route only after the code in onClick function gets executed.

    您可以在[此处]获取完整代码.(https://github.com/pushkalb123/basic-react-router/blob/master/src/App.js)

    You can get the entire code [here].(https://github.com/pushkalb123/basic-react-router/blob/master/src/App.js)

    推荐答案

    一种可能的方法是,不使用 Link,而是使用 history.push 动态改变路由.要实现这一点,请移除 Link 组件并在 li 上定义 onClick 事件.现在首先执行 onClick 函数内的所有任务,最后使用 history.push 更改路由方式以导航到其他页面.

    One possible way is, Instead of using Link, use history.push to change the route dynamically. To achieve that remove the Link component and define the onClick event on li. Now first perform all the task inside onClick function and at the end use history.push to change the route means to navigate on other page.

    在您的情况下,在 setState 回调函数中更改路由器以确保它仅在状态更改后发生.

    In your case change the router inside setState callback function to ensure that it will happen only after state change.

    这样写:

    <li key={i} onClick={() => props.selectName(name)}> {name} </li>
    
    selectName = (name) => {
        this.setState({ selectedName:name }, () => {
            this.props.history.push('about');
        });
    }
    

    检查这个答案:

    何时使用 setState 回调

    如何使用 react router dom 动态导航

    这篇关于如何在 Link: ReactJS 上使用 onClick 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆