如何在其他组件Reactjs上使用一些道具

时间:2019-01-16 12:00:56

标签: javascript reactjs react-router react-props react-component

我映射了电影(海报)列表,每个海报上都有按钮(观看),一旦单击按钮观看,它将带您到另一个组件(观看)。单击按钮后,如何将各个海报道具从“海报”组件传递到手表组件。

{this.state.Poster.map(poster =>
          <Col md="3 " className="" >
            <Card className="card-user card-transparent">
              <CardImg top src={`/files/${poster.filename}`}></CardImg>
                <CardText className="py-3 px-3">
                  <div className="card-description">
                  <h6 className="display-5  text-center">{poster.metadata.name}</h6>
                  <p className="text-center">{poster.metadata.Description}</p>
                  </div>
                  </CardText>
                <CardFooter>
                  <div className="button-container  py-3"><a href="watch">
                    <Button className="btn-fill btn-movie " color="primary" >
                      Watch
                    </Button></a>
                  </div>
                </CardFooter>
              </Card>
            </Col>
            )}

1 个答案:

答案 0 :(得分:1)

由于您在react-router | react-router-dom中提到了v4,因此可以通过以下两种方式之一进行操作:

A

  1. 替换为
<Link
  className="btn btn-primary" // some bootstrap class 
  to={{
    pathname: "/watch",
    state: { posterId: poster.id } // I am assuming  post has id
  }}
/>
  1. WatchComponent
class WatchComponent extends React.Component {
 componentDidMount() {
   const { posterId } = this.props.location.state;
   //make ajax request to the server and get poster details 
   //promise resolve, set response into state 
   // this.setState({ poster: res.json()})

 }
 render() {
   const { poster } = this.state;
   return (
     // render poster details here.
   )


 }
}

您只需完成

<Link
  className="btn btn-primary" // some bootstrap class 
  to={`/watch/${posterId}`} // provided that Route of WatchComponent is defined as (URL parameter) <Route path="watch/:posterId" component={WatchComponent} />
/>

然后在WatchComponent中执行

class WatchComponent extends React.Component {
 componentDidMount() {
   const { posterId } = this.props.macth.params;
   //make ajax request to the server and get poster details 
   //promise resolve, set response into state 
   // this.setState({ poster: res.json()})

 }
 render() {
   const { poster } = this.state;
   return (
     // render poster details here.
   )


 }
}