如何在卡片中单击锚标记并将我重定向到另一个页面,其中包含当前卡片示例的更多详细信息单击打开带有当前(单击)卡片详细信息的新选项卡这里是项目的api https://api.npoint.io/d275425a434e02acf2f7/News/0
的代码片段也可以链接https://codesandbox.io/s/sweet-spence-1tl4y5?file=/src/App.js
我的API https://api.npoint.io/d275425a434e02acf2f7用于呈现卡片中的所有项目
filteredCat?.map((list) => {
if (list.showOnHomepage === "yes") {
const date = format(
new Date(list.publishedDate),
"EEE dd MMM yyyy"
);
const showCat = news.map((getid) => {
if (getid.id == list.categoryID) return getid.name;
});
// const rec = list.publishedDate.sort((date1, date2) => date1 - date2);
return (
<Card
className=" extraCard col-lg-3"
style={{ width: "" }}
id={list.categoryID}
>
<Card.Img
variant="top"
src={list.urlToImage}
alt="Image"
/>
<Card.Body>
<Card.Title className="textTitle">
{list.title}
</Card.Title>
<Card.Text></Card.Text>
<small className="text-muted d-flex">
<FaRegCalendarAlt
className="m-1"
style={{ color: "#0aceff" }}
/>
{date}
</small>
<div
style={{ color: "#0aceff" }}
className="d-flex justify-content-between"
>
<Button variant="" className={classes["btn-cat"]}>
{showCat}
</Button>
<div>
<FaRegHeart />
<FaLink />
</div>
</div>
</Card.Body>
</Card>
);
}
})
}
</div>
}
我尝试了这种技术,但它确实引导我到同一个页面,而不是空页的新选项卡!!
function handleClick(event) {
event.preventDefault();
window.location.href = 'src/comp/newsitem';
}
function news() {
return (
<a href="#" onClick={handleClick}>
Click me to redirect!
</a>
);
}
React提供了spa,这意味着您可以加载不同页面的内容而无需任何刷新或重定向。所以不需要重定向到另一个页面,除非你真的想在一个新的选项卡中打开这个页面。
如果你想有多个页面路径,你应该使用react-router-dom。
所以首先你应该把你的路由添加到你的应用程序中。添加一个pages.js文件,内容如下:import { BrowserRouter, Routes, Route } from 'react-router-dom';
import App from './App';
import News from './News';
import NewsItem from './NewsItem';
function Pages() {
return (
<BrowserRouter>
<Routes>
<Route path='/news' element={<News />} />
<Route path='/newsItem' element={<NewsItem />} />
<Route path='/' element={<App />} />
</Routes>
</BrowserRouter>
);
}
export default Pages;
然后导入到index.js文件中:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import Pages from "./Pages";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<Pages />
</StrictMode>
);
NewsItem文件:
function NewsItem() {
return <div>News Item</div>;
}
export default NewsItem;
最后,当你想浏览新闻页面时,这样做:
import { Link } from 'react-router-dom'
<Link to='/news' />
或者如果你想在新选项卡中打开:
<Link to='/news' target='_blank' />
和导航到NewsItem页面(没有任何和)标签):
<Link to="/newsItem">News Item</Link>