[英]How to pass query parameters to another component in ReactJS?
Relatively new to React, and especially to Routing (with any framework) so please forgive me if this is a simple fix. React 相对较新,尤其是路由(使用任何框架),所以如果这是一个简单的修复,请原谅我。
I'm trying to route to another React component upon the click of a button on the parent/other component.我试图通过单击父/其他组件上的按钮来路由到另一个 React 组件。 The buttons represent Room numbers, and I want to pass the data of what room number I clicked to another component that will use that information to launch a query.这些按钮代表房间号,我想将我点击的房间号的数据传递给另一个组件,该组件将使用该信息启动查询。
I'm having difficulty with passing data to the component, and then from there launching the query.我很难将数据传递给组件,然后从那里启动查询。 I can detect what button is being pressed.我可以检测到按下了什么按钮。
How can I fix this?我怎样才能解决这个问题? Would love any pointers, and above all thank you for your time.会喜欢任何指示,最重要的是感谢您抽出宝贵时间。
In your route definition, you are expecting id
as a path parameter, but in the handleClick
code you are defining it as a query parameter.在您的路由定义中,您期望id
作为路径参数,但在handleClick
代码中,您将其定义为查询参数。 So you need to change your path generation logic as below.所以你需要改变你的路径生成逻辑如下。
this.props.history.push("/RoomTiles/" + this.buttonClicked);
Updated更新
Since you are not passing any custom props from the App.js
to the RoomTiles
component, you can simply define the Route
as follows.由于您没有将任何自定义道具从App.js
传递到RoomTiles
组件,因此您可以简单地定义Route
,如下所示。
<Route path="/RoomTiles/:id" component={RoomTiles}/>
The history.push
should push the id
as a URL param. history.push
应该将id
作为 URL 参数推送。 Not as a query param.不作为查询参数。
this.props.history.push(`/RoomTiles/${this.buttonClicked}`);
And int RoomTiles
component, you could use useParams
to read the param.和 int RoomTiles
组件,您可以使用useParams
来读取参数。
const RoomTiles = (props) => {
let { roomId } = useParams();
return <div>Now in {roomId}</div>;
}
Documentation of useParams
here: useParams
文档在这里:
https://reactrouter.com/web/api/Hooks/useparams https://reactrouter.com/web/api/Hooks/useparams
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.