简体   繁体   中英

Pass value to another component in ReactJs on onClickEvent not working

I am passing the value to another component onclickEvent, but value won't pass to another component and shows null reference.

I have two component they are DriverCards and DriverPendingOrders. I want to pass value of orderId from DriverCards to DriverPendingOrders.

Below is my two working component.

this is DriverCard Component

import React, { Component } from 'react';
import { connect } from "react-redux";
import PropTypes from "prop-types";

export default class DriverCard extends Component{

    constructor(props) {
        super(props);
    } 

    render(){

        let { OrderID,CID,DeliveryEst,DeliveryInstructions,DriverID,Orders,PrepInsruction,RID,Status,Total } = this.props.indOrder;

        return(

            <div class="container">
                <div class="card" style={{width:'100%',borderRadius:'2%', border: '4px solid lightgreen'}}>
                    <div class="card-body" style={{textAlign:'center'}}>
                        <h4 class="card-title">{CID}</h4>
                        <p class="card-text"><h5>{RID}</h5></p>
                        {/* <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> */}

                        <button type="button" onClick={() => {this.props.removeOrder(OrderID);this.props.showOrder.bind(this,OrderID)}}class="btn btn-success btn-sm" style={{width:'50%'}}>Accept</button> 


                        <button type="button" class="btn btn-danger btn-sm" style={{width:'50%'}}>Decline</button>
                    </div>
                </div>
            </div>
        )
    }
}

And Below is DriverPendingOrder Component where I want to get orderID passed from DriverCard.

import React, { Component } from 'react'
import { connect } from "react-redux";
import PropTypes from "prop-types";
import DriverPendingCard from './DriverPendingCard';


export class DriverPendingOrders extends Component{

    constructor() {
        super();
        this.state = {
            Orderslist: [
              {
                  OrderID:parseInt("001"),
                CID:123,
                DeliveryEst:"",
                DeliveryInstructions:"Door",
                DriverID:"",
                Orders:"ABC",
                PrepInsruction:"Mild",
                RID:"A",
                Status:"",
                Total:""

              },
              {   
                  OrderID:parseInt("002"),
                  CID:456,
                  DeliveryEst:"",
                  DeliveryInstructions:"Front Door",
                  DriverID:"",
                  Orders:"BCD",
                  PrepInsruction:"Medium",
                  RID:"B",
                  Status:"",
                  Total:""
              },
              {
                  OrderID:parseInt("003"),
                  CID:678,
                  DeliveryEst:"",
                  DeliveryInstructions:"Gate",
                  DriverID:"",
                  Orders:"DEF",
                  PrepInsruction:"Spicy",
                  RID:"C",
                  Status:"",
                  Total:""
              }
            ]
          }

    }
      showOrder(OrderID) {



        this.setState({ Orderslist: this.state.Orderslist.filter(order=> order.OrderID == OrderID)});

      }
    render(){
        let dCard1 = this.state.Orderslist.map(order => {
            return (
              <DriverPendingCard key={order.OrderID} showOrder={this.showOrder.bind(this)} inOrder1={order}/>

            )
          })

        return(

            <div>
                <ul class="list-group">

                    {dCard1}

                </ul>
            </div>
        )
    }
}

export default DriverPendingOrders;

Try that

DriverCard:

<button onClick={this.add}>Add</button>
...
...
  add = () => {
    this.props.passId(id);
}

DriverPendingOrder:

 import { DriverCard } from "../DriverCard";
   ...
   ...
 <DriverCard passId={this.changedId}/>
    ...
    ...
    changedId = passedId => {
        this.setState({
          id: passedId
        });
      };

The problem is in the following part

 <button type="button" onClick={() => {.....;this.props.showOrder.bind(this,OrderID)}}... 

Function.prototype.bind() doesnot call the function it returns a new function that need to called if you using wrapper function.Just need to call the showOrder after binding.

The bind() method creates a new function that, when called, has its this keyword set to the provided value

 <button type="button" onClick={() => {this.props.removeOrder(OrderID);this.props.showOrder.bind(this,OrderID)()}}class="btn btn-success btn-sm" style={{width:'50%'}}>Accept</button> 

Below are two vanila js example to see the difference

Non-Working

 function myFunc(){ console.log('clicked') } document.querySelector('button').addEventListener('click',(e) => { myFunc.bind(this); //not called }) 
 <button>Click me!</button> 

Working

 function myFunc(){ console.log('clicked') } document.querySelector('button').addEventListener('click',(e) => { let temp = myFunc.bind(this) //not called console.log(typeof temp); //function temp(); //funtion called }) 
 <button>Click me!</button> 

From Children to Parent

Parent

<ChildComp from_children={(val)=>console.log(val)}/>

Children

to_Parent=()=>{
this.props.from_children(val);
}

<Button onclick={()=>to_Parent()}>

  <DriverPendingCard key={order.OrderID} **showOrder={()=>this.showOrder(OrderID)**} inOrder1={order}/> 
这样写,如果你想传递价值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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