简体   繁体   English

如何在反应链接组件上使用 onClick 事件?

[英]How to use onClick event on react Link component?

I am using the Link component from the reactjs router and I cannot get the onClickevent working.我正在使用 reactjs 路由器中的 Link 组件,但我无法让 onClickevent 正常工作。 This is the code:这是代码:

<Link to={this.props.myroute} onClick='hello()'>Here</Link>

Is this the way to do it or another way?这是这样做的方式还是其他方式?

You are passing hello() as a string, also hello() means execute hello immediately.你逝去的hello()作为一个字符串,也hello()方法执行hello马上。

try尝试

onClick={hello}

You should use this:你应该使用这个:

<Link to={this.props.myroute} onClick={hello}>Here</Link>

Or (if method hello lays at this class):或者(如果方法hello位于此类中):

<Link to={this.props.myroute} onClick={this.hello}>Here</Link>

Update: For ES6 and latest if you want to bind some param with click method, you can use this:更新:对于 ES6 和最新版本,如果你想用 click 方法绑定一些参数,你可以使用这个:

    const someValue = 'some';  
....  
    <Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>

I don't believe this is a good pattern to use in general.我不相信这是一般使用的好模式。 Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. Link 将运行您的 onClick 事件,然后导航到路线,因此导航到新路线会有轻微的延迟。 A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function.更好的策略是像您所做的那样使用“to”道具导航到新路线,并且在新组件的 componentDidMount() 函数中,您可以触发 hello 函数或任何其他函数。 It will give you the same result, but with a much smoother transition between routes.它将为您提供相同的结果,但路线之间的过渡更加平滑。

For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component.对于上下文,我在更新我的 redux 存储时注意到了这一点,就像你在这里一样,在链接上使用 onClick 事件更新我的 redux 存储,并且在安装新路由的组件之前它导致了大约 0.3 秒的空白屏幕延迟。 There was no api call involved, so I was surprised the delay was so big.没有涉及 api 调用,所以我很惊讶延迟这么大。 However, if you're just console logging 'hello' the delay might not be noticeable.但是,如果您只是在控制台记录“hello”,则延迟可能不会很明显。

 const onLinkClick = (e) => {
    e.preventDefault();
    ---do your stuff---
    history.push('/your-route');
};

<a href='/your-route' onClick={onLinkClick}> Navigate </a>
                   or
<Link to='/your-route' onClick={onLinkClick}> Navigate </Link>
1) Link to use in react onClick event
<a href="#" onClick={this.setActiveTab}>
      ...View Full List
                    </a>

  setActiveTab = (e) => {
    e.preventDefault();
    console.log(e.target);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM