在React-Router中通过Link传递道具 [英] passing props with Link in React-Router
问题描述
您好,我正在尝试使用来自React Router的链接组件将道具传递给Details
组件.我不想在页面上显示Detail
组件,单击按钮时它应该呈现,但是当新组件呈现时,URL看起来也应该像这样的"/details/KvhNJecsqr6JFMSRTS".
Hello i'm trying to pass Props to a Details
Component with the Link Component from React Router. I don't want to display the Detail
Component on the page, it should render when a button is clicked but also the url should look like this '/details/KvhNJecsqr6JFMSRTS' when the new Component renders.
class Card extends Component {
render(props){
return(
<Col xs={12} md={4}>
<Thumbnail src="./someiamge">
<h3>{this.props.cardHeading}</h3>
<p>{this.props.cardDesc}</p>
<Button bsStyle="primary">Mieten</Button>
<Button bsStyle="default"><Link to='/details' params={{cardId: this.props.cardId}} 'here i wanna pass some props how i do this ?' >Details</Link></Button>
</Thumbnail>
</Col>
)
}
}
export default Card
这是我的路由器的东西
<BrowserRouter>
<div>
<Route name='details' path='/details/:cardId' component={Details}/>
</div>
</div>
</BrowserRouter>
hier是我的Details
组件:
hier is my Details
Component:
class Details extends Component {
render() {
return (
<div >
<div style={{textAlign: "left"}}>
<h3>{this.props.cardHeading}</h3>
<p>{this.props.cardDesc}</p>
.......
</div>
</div>
);
}
}
export default Details;
推荐答案
如果希望您的新路由类似于/details/:cardId,那么我想这应该就足够了:
If want your new route to be like /details/:cardId, then I guess this should be enough:
<Link to={`/details/${this.props.cardId}`} />
但是,如果您想添加一些额外的属性,请按照文档,您可以在location.state
中传递它们:
But, if you want to add some extra properties, then according to documentation, you could pass them in the location.state
:
<Link to={{
pathname: `/details/${this.props.cardId}`,
state: {
cardHeading: 'This is a heading',
cardDesc: 'Description'
}
}}/>
然后,为了访问组件中的此状态,可以使用this.props.location.state
或this.props.history.location.state
Then, in order to access this state in your component, you can use the this.props.location.state
or this.props.history.location.state
这篇关于在React-Router中通过Link传递道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!