当用户单击这样的按钮时,我试图重定向到另一个组件:
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;
但是目前,当用户单击按钮时,什么都没有发生,如何实现重定向到所需组件的方法?
答案 0 :(得分:1)
您可以使用props.history.push();
或Router.push();
函数。
答案 1 :(得分:0)
react-router
支持程序化路由;无需渲染新组件。 (顺便说一下,onClick应该可以做一些事情,现在它只返回一个返回一个react组件的回调,这没有意义,因为onClick
甚至不应该具有返回值!)< / p>
我也不知道为什么要在路由器中包装一个组件。您的应用程序的顶层应该有一个路由器,其中包含每个单独的路由。
假设您将posts组件放置在应用程序中其他位置的router组件中:
import { withRouter } from 'react-router-dom'
const Posts = withRouter(({ history, posts, loading }) => {
if (loading) {
return <div class="loader">
<div class="spinner"></div>
</div>
}
// Removed the <Router> component because it can't route to anything else properly that way.
// Have every component in your app be in a single router at the top level.
return (
<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={() => history.push('/article')}>Read more</button>
</div>
</div>
</div>
))}
</div>
);
});
export default Posts;
history
道具是使用withRouter
提供给组件的,可用于通过push
或replace
转到新位置。它基于history NPM package。
答案 2 :(得分:0)
您可以使用<Link>
进行重定向。
import { Link } from 'react-router-dom';
const Posts = ({ posts, loading }) => {
if (loading) {
return <div class="loader">
<div class="spinner"></div>
</div>
}
return (
<Router>
<Route path="/article" component={Article}/>
<div className="post-container">
<Link
className="read-more-btn" // give button's css to link
to='/article' // redirect
>
Read more
</Link>
</div>
</Router>
);
};
export default Posts;
注意:-您不能使用history.push()重定向组件,因为在使用历史记录道具时,您需要像withRouter(YourComponent)
这样绑定组件并在代码中进行绑定它会给您类似"You should not use <withRouter(YourComponent) /> outside a <Router>"
的错误。如果要使用history.push(),则需要将两个文件分别用于路由和一个重定向文件。