[英]How do I pass a variable from one component to another?
I'd like to pass the name variable in SingerBox.js to the Album component so I can display an artist's albums.我想将 SingerBox.js 中的 name 变量传递给 Album 组件,以便显示艺术家的专辑。 When I print props.name, it's undefined.
当我打印 props.name 时,它是未定义的。 How do I pass it properly?
如何正确通过?
SingerBox.js歌手盒子.js
import React, { Component } from "react";
import Modal from "react-bootstrap/Modal";
import ImageNotFound from "../../ImageNotFound.jpg";
import "../../App.css";
import { Link } from "react-router-dom";
import Albums from "../Albums/Albums";
const SingerCard = (props) => {
const { images, name, artists } = props;
//check if the image array is empty since some artists' image data provided by the API call are empty
const singer_img = images.length === 0 ? ImageNotFound : images[0].url;
return (
<>
<Link to="/albums" onClick={() => <Albums name={name} />}>
<div className="box">
<div>
<img className="singer-img" src={singer_img} alt="Card image" />
{name}
</div>
</div>
</Link>
</>
);
};
export default SingerCard;
Albums.js相册.js
import React, { Component } from "react";
const Albums = (props) => {
return <div style={{ color: "white" }}> {`${props.name}'s albums`}</div>;
};
export default Albums;
The result is "undefined's albums".结果是“未定义的专辑”。
In your case, you attempt to pass the variable through the <Link>
with react-router-dom .在您的情况下,您尝试使用react-router-dom通过
<Link>
传递变量。 Thus, I assume you would like to pass a variable between <Routes>
.因此,我假设您想在
<Routes>
之间传递一个变量。
You can use URL Parameter or Query Parameter to pass the variable between routes.您可以使用URL 参数或查询参数在路由之间传递变量。
URL Parameter example: URL 参数示例:
https://reacttraining.com/react-router/web/example/url-params https://reacttraining.com/react-router/web/example/url-params
Query Parameter example:查询参数示例:
https://reacttraining.com/react-router/web/example/query-parameters https://reacttraining.com/react-router/web/example/query-parameters
I had wrote an example of URL Paramater for your reference:我写了一个 URL 参数示例供您参考:
https://codesandbox.io/s/react-query-param-example-1ol6u https://codesandbox.io/s/react-query-param-example-1ol6u
Good luck.祝你好运。
You can do what @YingHua mentioned in answer and one more thing you can do is like below.你可以做@YingHua 在回答中提到的事情,你可以做的另一件事如下所示。
OnClick you can call one function and from that function you can redirect with data. OnClick 你可以调用一个 function 并且从那个 function 你可以用数据重定向。
this.props.history.push({
pathname: '/somewhere',
state: { fromDashboard: true }
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.