gpt4 book ai didi

javascript - 如何在React中点击时重定向到组件

转载 作者:行者123 更新时间:2023-12-02 22:38:31 24 4
gpt4 key购买 nike

当用户单击这样的按钮时,我尝试重定向到另一个组件:

import React from 'react';
import Article from '../Article/Article.js'
import { BrowserRouter as Router, Route, Switch, Redirect} from 'react-router-dom'


const Posts = ({ posts, loading }) => {
if (loading) {
return <div class="loader">
<div class="spinner"></div>
</div>
}


return (
<Router>
<div className="post-container">
{posts.map(post => (
<div key={post._id} className='post'>
<img className="post-container__image" src={post.picture} alt="image"/>
<div className="post-container__post">
<div className="post-container__text">
<h2 className="post-container__title">{post.title}</h2>
<p className="post-container__date">{post.date}</p>
<p className="post-info-container__text">{post.postContent.substring(0, 500) + "..."}</p>
<button className="read-more-btn" onClick={() => () => <Route path="/article" component={Article}/>}>Read more</button>
</div>
</div>
</div>
))}
</div>
</Router>
);
};

export default Posts;

但是目前当用户单击按钮时没有任何反应,我如何实现到所需组件的重定向?

最佳答案

您可以使用 props.history.push();Router.push(); 函数。

关于javascript - 如何在React中点击时重定向到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58663605/

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