[英]Send variable from one component to another in react
I have created a routing where the component ProductId will be rendered (a href="/id")when there is a click on div with class name="card"我创建了一个路由,当单击带有 class name="card" 的 div 时,将在其中呈现组件 ProductId (a href="/id")
<a href="/id"> <div className="card"> <div className="imgBx"> <h1>Product</h1> <img src={image} alt={image} className="myProductImage" /> </div> <div className="content"> <div className="productName"> <h3>{name}</h3> </div> <div className="price_rating"> <div className="price">{price} $</div> <div className="ratings"> {ratings} <i className="fa fa-star"></i> </div> </div> </div> </div> </a>
The Route is defined as following:路由定义如下:
ReactDOM.render( <BrowserRouter> <Switch> <Route path="/id" component={ProductId}/> <Route path="/" exact component={Products}/> </Switch> </BrowserRouter>,document.getElementById("root") );
Now when the component ProductId is rendered I want to pass props (_id), (this props is present in the component where the onClick event is taking place) with onClick but since I am not calling the directly I cannot pass the props like.现在,当呈现组件 ProductId 时,我想通过 onClick 传递道具 (_id),(此道具存在于发生 onClick 事件的组件中),但由于我没有直接调用,所以我无法像这样传递道具。
Is there any other way where I can pass the props to the ProductId component when there is an onClick event on div with class name="card"当 class name="card" 上的 div 上有 onClick 事件时,有没有其他方法可以将道具传递给 ProductId 组件
If i understand correctly, you should use a dynamic route that contain the product id
如果我理解正确,您应该使用包含产品
id
的动态路由
For example:例如:
<Router>
<Route path="/product/:id" component={ProductId} />
</Router>
Then your ProductId
component will receive the id
from the router params in props.match.params.id
然后您的
ProductId
组件将从props.match.params.id
中的路由器参数接收id
see https://reactrouter.com/web/api/Route/component参见https://reactrouter.com/web/api/Route/component
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.