【问题标题】:How use some props on other components Reactjs如何在其他组件 Reactjs 上使用一些 props
【发布时间】:2023-03-21 06:25:01
【问题描述】:

我通过电影(海报)列表进行映射,我在每张海报上都有按钮(观看),一旦您单击按钮观看,它将带您到另一个组件(观看)。如何在单击按钮时将单个海报道具从海报组件传递到手表组件。

{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>
            )}

【问题讨论】:

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


【解决方案1】:

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

一个

  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.
   )


 }
}

【讨论】:

  • 谢谢让我试试看
  • 另一种方式,没有 react-router-domm 可以将 Card 作为组件并附加一个回调,说它 getId 给它,然后在按下按钮时触发后者并传回 @ 987654329@ 到父组件,它将重新渲染并将 postId 传递给WatchComponent。这需要组件生命周期,例如 componentDidUpdate 和更多调整。
  • @SadiqMustaphaAji 你好,这个问题解决了吗?
  • 请你给我举个例子吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 2019-04-03
  • 2020-04-24
  • 1970-01-01
  • 2013-01-18
相关资源
最近更新 更多