在 URL 中設置動態參數傳遞給指定參數組件。
在App.js 的Route path="/cards/:title",指定參數,並將data[]陣列物件放在App.js中,利用(props)傳遞數據至AllCard.js,在AllCard.js中用filter()篩選同樣的參數頁面加以顯示。
data.filter(card => card.title === title)
App.js
import React from 'react';
import { BrowserRouter as Router,Route } from 'react-router-dom';
import "./App.css";
import User from "./User";
import AllCard from "./AllCard";
const App = () => {
const data = [
{
title : "Tokyo",
image:"image/tokyo01.jpg",
description:"This is Tokyo Page"
},
{
title : "Osaka",
image:"image/osaka.jpg",
description:"This is Osaka Page"
},
{
title : "Fukuoka",
image:"image/fukuka.jpg",
description:"This is Fukuoka Page"
},
{
title : "Kyoto",
image:"image/kyoto.jpg",
description:"This is Kyoto Page"
},
{
title : "Kobe",
image:"image/kobe.jpg",
description:"This is Kobe Page"
},
{
title : "Hokkaido",
image:"image/hokkaido.jpg",
description:"This is Hokkaido Page"
},
];
return (
<Router>
<Route exact path="/">
<User data={data} />
</Route>
<Route path="/cards/:title">
<AllCard data={data} />
</Route>
</Router>
)
}
export default App
AllCard.js
import React from 'react';
import { useParams } from 'react-router-dom';
const AllCard = ({data}) => {
const {title} = useParams();
return (
<>
<section className="all">
<div className="container">
{data.filter(card => card.title === title).map((card,index) =>(
<div key={index} className="allcard">
<h1>{card.title}</h1>
<p>{card.description}</p>
</div>
))}
</div>
</section>
</>
)
}
export default AllCard
User.js
import React from 'react';
import Card from "./Card";
const User = ({data}) => {
return (
<section className="user">
<div className ="container">
<Card data={data} />
</div>
</section>
)
}
export default User;
Card.js
import React from 'react';
import { Link } from 'react-router-dom';
const Card = ({data}) => {
return (
<>
{data.map((card,index)=>(
<div key={index} className="card">
<h1>{card.title}</h1>
<img src={card.image} />
{/*<p>{card.description}</p>*/}
<Link to={`/cards/${card.title}`}>View More</Link>
</div>
))}
</>
);
};
export default Card;