How to use onClick event on react Link component?

2019-02-05 15:42发布

I am using the Link component from the reactjs router and I cannot get the onClickevent working. This is the code:

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

Is this the way to do it or another way?

3条回答
成全新的幸福
2楼-- · 2019-02-05 16:12

You should use this:

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

Or (if method hello lays at this class):

<Link to={this.props.myroute} onClick={this.hello}>Here</Link>
查看更多
男人必须洒脱
3楼-- · 2019-02-05 16:24

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. 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. 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. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.

查看更多
闹够了就滚
4楼-- · 2019-02-05 16:30

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}
查看更多
登录 后发表回答