gpt4 book ai didi

javascript - 单击特定卡时在另一页上呈现卡详细信息

转载 作者:行者123 更新时间:2023-12-02 23:18:20 25 4
gpt4 key购买 nike

卡片来自 JSON 文件。代码来自名为 Paintings.js 的文件。卡片全部正确渲染,单击时它们将我带到空白的 PaintingInfo.js 页面。我的问题是我应该在这个新的 PaintingInfo.js 页面中包含什么,以便它呈现我存储在 localstorage 中的卡片。对于 React 来说相对较新,因此我们将不胜感激。基本上,我如何访问 PaintingInfo.js 页面中的本地存储以进行渲染?

  state = {
cardInfo: [...cardInfo]
};

goToPaintingInfo = (cardInfo) => {
localStorage.setItem("selectedPainting", cardInfo);
this.props.history.push("/paintingInfo/:id");
}

render() {
return (
<React.Fragment>
<Navbar className="navCustom d-flex justify-space-between" bg="light" variant="light">
<Navbar.Brand href="/">SNR Arts</Navbar.Brand>
<Nav className="ml-auto navCust">
<Nav.Link href="/">Home</Nav.Link>
<Nav.Link href="/paintings">Paintings</Nav.Link>
<Nav.Link href="/contact">Contact</Nav.Link>
</Nav>
</Navbar>
<div className="container-fluid">
<div className="row align-items-center justify-content-between">
{/* print out cards here */}

{this.state.cardInfo.map(card => {
return (
<div className="col-12 col-sm-3 col-md-2 my-3" key={card.id}>
<img
src={card.image}
alt={card.name}
className="img-fluid img-thumbnail rounded indvCard bg-dark"
onClick = {()=>this.goToPaintingInfo(card.id)}
/>
</div>
);
})}
</div>
</div>

最佳答案

点击卡片时,您只需发送card,而不是card.id

onClick = {()=>this.goToPaintingInfo(card)}
goToPaintingInfo = (cardInfo) => {
localStorage.setItem("selectedPainting", JSON.stringify(cardInfo)); //store complete card
this.props.history.push(`/paintingInfo/${cardInfo.id}`); //For this you must have Route to handle this request
}

在路线的某个地方,你必须有

<Route path="/paintingInfo/:id" exact component={paintingInfo} /> //Write appropriate component name

paintingInfo.js 文件

state={
card: JSON.parse(localStorage.getItem("selectedPainting"))
}

render(){
return(
<div>
<img src={this.state.card.image}
alt={this.state.card.name}
className="img-fluid img-thumbnail rounded indvCard bg-dark"
/>
</div>
)
}

注意:您可以使用 react-router- 中的 Redirect 来代替 this.props.history.push仅 dom 包。

import {Redirect} from 'react-router-dom'
goToPaintingInfo = (cardInfo) => {
localStorage.setItem("selectedPainting", cardInfo); //store complete card
return <Redirect to={`/paintingInfo/${cardInfo.id}`} />; //For this you must have Route to handle this request
}

关于javascript - 单击特定卡时在另一页上呈现卡详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57067355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com