Pass props to another component onclick of a button

后端 未结 2 1637
终归单人心
终归单人心 2021-01-15 09:55

In my nextJS app, I want to pass props of one component to another which is neither a parent nor child of first component.How can I do that?

There is a Order

2条回答
  •  感动是毒
    2021-01-15 10:35

    In your case you need to deal with callbacks. Callback is a concept in react.

    Declare an event handler function in orders.js which sets the orderId to the state when button clicked in orders.js component and pass down that event handler function to Order component as props and pass down orderId as a prop to OrderViewer component

    orders.js

      constructor(props){
          super(props);
          this.state = {
               orderId: null
          }
      }
      handleViewOrder = orderId = {
          this.setState({
              orderId
          });
      }
      render(){
        return(
    )}

    Now in order.js access the received handler function using props and assign it to button onClick by passing orderId

       

    {this.props.orderno} {this.props.title}

    {this.props.entity} - {this.props.po}

    Due {this.props.duedate}

    Now, you can access orderId using this.props.orderId in OrderViewer component and display it

    OrderViewer.js

       
    {this.props.orderId}

    So having an event handler function in parent component and passing down as props to child component and assigning to child component button onClick and when clicked changing parent state is so called callbacks in react. If you understand what I am trying to explain in my answer you can get going easily

    Edit:

    In Order.js component

    Change

      
    

    To

       
    

    Also you are calling Order component in loop but you are not setting unique key to Order component so

    Change

                { Orders.map((order) =>  )}
    

    To

                { Orders.map((order) =>  )}
    

提交回复
热议问题