简体   繁体   中英

send data through onclick event from child to parent React js?

I am new to React js I am pretty confused that how to send data through onclick event from child to parent component.

Parent Component

...
      onTurn(id){
            console.log(id)//undefined
        }
        renderCardsList(){
              const {cardsList} = this.props

              return cardsList.get('cards').map(({id,front_image}) => {
                  return  <Card
                            image={front_image}
                            onTurn={this.onTurn}
                            />
              })

            }
...

Child Component

const Card = (props) => {
    return(
        <div className="singleCard">
            <div className="imageDiv">
                <img src={props.image} alt="work" />
            </div>
            <div className="bottombar">
                <span onClick={e => props.onTurn(props.id)} className="glyphicon glyphicon-refresh" />
                <span className="glyphicon glyphicon-pencil" />
                <span className="glyphicon glyphicon-pushpin"  />
            </div>
        </div>
    )
};

Your onClick expects an id property on props :

onClick={e => props.onTurn(props.id)}

But you're not providing one:

return  <Card
    image={front_image}
    onTurn={this.onTurn}
    />

So naturally, props.id in the card's render is undefined .

If you want the card to have an id on props , you'll need to specify one, eg:

return  <Card
    image={front_image}
    onTurn={this.onTurn}
    id={/*something*/}
    />

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