【发布时间】:2021-08-22 04:01:14
【问题描述】:
我正在构建一个图库,您在其中单击图像,它将使用道具加载到单独的组件中,该图像是一个 URL,取自硬编码数组,其中 src 通过 CSS 作为背景图像加载.我的挑战是将数据连接到该组件。我尝试使用回调将数据从父级连接到子级,但没有运气。我想我正在尝试做的是横向连接组件,我不想使用redux,因为我不熟悉。
注意:我知道您可以使用 window.location.href = "props.src/" 在 GalleryContainer.js 中加载图像,但是,我希望图像加载到 Image 组件中,该组件将充当容器来保存图像,为用户提供其他选项比如下载图片等等……
注意:我已经尝试在 Gallery.js 中导入 Image 组件并像这样渲染它:<Image src={props.src} id={props.id}/>,我发现数据连接得很好,但这无助于保持组件分离。
我已经拥有的: 我在 app.js 中有一个路由,它允许我去图像路由路径就好了,它从图像组件中的 props.src 加载到 URL 中,这是我的挑战
更新:已解决 Click here to see the solution!
代码如下:
GalleryList.js
import Gallery from "./Gallery";
import Header from "./UI/Header";
import Footer from "./UI/Footer";
import styles from "./Gallery.module.css";
const DUMMY_IMAGES = [
{
id: "img1",
src: "https://photos.smugmug.com/photos/i-vbN8fNz/1/X3/i-vbN8fNz-X3.jpg",
},
{
id: "img2",
src: "https://photos.smugmug.com/photos/i-fSkvQJS/1/X3/i-fSkvQJS-X3.jpg",
},
{
id: "img3",
src: "https://photos.smugmug.com/photos/i-pS99jb4/0/X3/i-pS99jb4-X3.jpg",
},
];
const GalleryList = () => {
const imagesList = DUMMY_IMAGES.map((image) => (
<Gallery id={image.id} key={image.id} src={image.src} />
));
return (
<>
<Header />
<ul className={styles.wrapper}>
<li className={styles.list}>{imagesList}</li>
</ul>
<a href="/">Home</a>
<Footer />
</>
);
};
export default GalleryList;
图库.js
import GalleryConatiner from "./UI/GalleryContainer";
import styles from "./Gallery.module.css";
const Gallery = (props) => {
return (
<>
<div className={styles["gal-warp"]}>
<GalleryConatiner id={props.id} key={props.id} src={props.src} />
</div>
</>
);
};
export default Gallery;
GalleryContainer.js
import styles from "../Gallery.module.css";
const GalleryConatiner = (props) => {
const selectedImg = () => {
if (props.id) {
// window.location.href = `image/${props.src}`;
window.location.href = "image/"
}
};
return (
<ul>
<li className={styles["gallery-list"]}>
<div
onClick={selectedImg}
className={styles["div-gallery"]}
style={{
backgroundImage: `url(${props.src}`,
height: 250,
backgroundSize: "cover",
}}
></div>
</li>
</ul>
);
};
export default GalleryConatiner;
Image.js
import styles from "./Image.module.css";
const Image = (props) => {
return (
<section>
<h1 className={styles["h1-wrapper"]}>Image:{props.id}</h1>
<div className={styles.wrapper}>
<div
className={styles["image-container"]}
style={{
backgroundImage: `url(${props.src}`,
}}
></div>
</div>
</section>
);
};
export default Image;
【问题讨论】:
-
您可以使用模态视图显示当前图像并下载但在那里。
-
@AmilaSenadheera,谢谢我知道我可以使用模态但我希望组件加载到另一个页面中
-
好的,那么您应该为此使用反应路由器。在根文件中设置交换机和路由
-
我在 app.js 中有一个不是我的问题的路由,我可以去图像路由就好了,它是从问题的图像组件中的 props.src 加载到 URL 中跨度>
标签: javascript reactjs components react-props