简体   繁体   English

React Router:将道具传递给嵌套的动态页面

[英]React Router: Pass Props to Nested, Dynamic Pages

Rendering Result components using map and passing props.使用map和传递道具渲染Result组件。

<div className="results">
  {data.map((movie) => (
    <Result
      poster={movie.poster_path}
      alt={movie.title}
      key={movie.id}
      id={movie.id}
    />
  ))}
</div>

My Result component that receives props接收道具的我的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>
  );
}

I have my dynamic routes.我有我的动态路线。

<Route path={"/results/:id"}>
   <ResultPage />
</Route>

I have my dynamic ResultPage , but I don't know how to pass the Result component's props to this page.我有我的动态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>
  );
}

Instead of Link component I have added an onClick event handler to the img tag and then in the handleClick method I'm useHistory.push() to send props from the Result Component to ResultPage component.我在img标签中添加了一个onClick事件处理程序,而不是Link组件,然后在handleClick方法中,我使用了useHistory.push()props从 Result 组件发送到ResultPage组件。

The location object has a state property, which now contains the props passed through the Result Component. location object 有一个state属性,它现在包含通过Result组件传递的props

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM