[英]React Router: Pass Props to Nested, Dynamic Pages
map
和传递道具渲染Result
组件。<div className="results">
{data.map((movie) => (
<Result
poster={movie.poster_path}
alt={movie.title}
key={movie.id}
id={movie.id}
/>
))}
</div>
Result
组件export default function Result(props) {
const { poster, alt, id } = props;
return (
<div className="result">
<Link to={`/results/${id}`}>
<img
src={
poster
? `https://image.tmdb.org/t/p/original/${poster}`
: "https://www.genius100visions.com/wp-content/uploads/2017/09/placeholder-vertical.jpg"
}
alt={alt}
/>
</Link>
</div>
);
}
<Route path={"/results/:id"}>
<ResultPage />
</Route>
ResultPage
,但我不知道如何将Result
组件的道具传递给这个页面。export default function ResultPage(props) {
const { id } = useParams();
return (
<div className="resultPage">
<h3>this is page: {id}</h3>
{/* I WANT TO PASS & DISPLAY PROPS HERE */}
</div>
);
}
Result.jsx
export default function Result(props) {
const { poster, alt, id } = props;
const history = useHistory();
const handleClick = () => {
history.push({
pathname: `/results/${id}`,
state: {
poster,
alt
}
})
}
return (
<div className="result">
<img
onClick ={handleClick}
src={
poster
? `https://image.tmdb.org/t/p/original/${poster}`
: "https://www.genius100visions.com/wp-content/uploads/2017/09/placeholder-vertical.jpg"
}
alt={alt}
/>
</div>
);
}
ResultPage.jsx
export default function ResultPage(props) {
const { id } = useParams();
const location = useLocation();
return (
<div className="resultPage">
<h3>this is page: {id}</h3>
<p> {location.state.poster} </p>
</div>
);
}
我在img
标签中添加了一个onClick
事件处理程序,而不是Link
组件,然后在handleClick
方法中,我使用了useHistory.push()
将props
从 Result 组件发送到ResultPage
组件。
location
object 有一个state
属性,它现在包含通过Result
组件传递的props
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.