向react组件的onClick添加链接



我想将onClick事件添加到我的组件中,该事件会导致单击,并通过使用"链接到路由器元素"将我引导到新页面。

我试过下面的代码:

import React from "react";
import { Link } from "react-router-dom";
export default function NewsItemBox(props: NewsItemBoxOptions) {
return (
<div className="col-lg-4 col-md-6" onClick={()=>{<Link to="./"></Link>}}>
<div className="single-blog-post">
hello world   
</div>
</div>
);
}`

为什么不使用history.push()

Route传递的props中有一个history对象。

export default function NewsItemBox(props: NewsItemBoxOptions) {
const { history } = props; 
return (
<div className="col-lg-4 col-md-6" onClick={()=> history.push("/anotherpage")}>
<div className="single-blog-post">
hello world   
</div>
</div>
);
}`

使用history.pushhistory的对象由Route组件提供,就像在调用<Route render={props => <NewsItemBox {...props} />} />时一样,这些道具包含history,它本身具有可以帮助您的有用函数。

这就是我在嵌套组件中获取history道具的方法。因此,我不必使用任何其他依赖项来获得嵌套组件中的history对象。

App.js

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
return (
<Provider store={store}>
<Router>
<div className="app ">
<Switch>
<Route exact path="/" component={Home} />
</Switch>
</div>
</Router>
</Provider>
);

Home.js在这里您可以访问history道具。因此,将其传递给子组件,因为子组件无法访问history道具。我注意到只有Route组件可以访问history道具

return (
<div>
<AnotherComponent history={this.props.history}/>
</div>
);

AnotherComponent.js

return (
<div>
<div> <h4>hello dear world</h4> </div>
{this.someLogic ? this.props.history.push("/new-page"): this.props.history.push("/amazing-page")}
</div>
);

最新更新