简体   繁体   中英

How to pass a paramater in the onclick event in React (Could not get the value)

I could not get the expected value so guys please help me out guys The code should run and each time when the button is clicked it should increment one time and have an id but it shows me that in the render method product is not defined

import React, { Component } from 'react';

class Counter extends Component {
    state = {
        count: 0
     
    }

    //constructor() {
    //    super();
    //    this.handleIncreement = this.handleIncreement.bind(this);
    //}

    handleIncreement = product => {
        console.log(product);
        this.setState({ count: this.state.count + 1});
    }

    render() { 
        return (
            <div>
            
            <span className={this.handlebadgeClasses()}>{this.handleCounter()}</span>
            <button onClick={ () =>this.handleIncreement(product) } className="btn btn-secondary btn-sm">Increement</button>
            
            </div> 
          );
    }

    handlebadgeClasses() {
        let classes = "badge m-2  badge-";
        classes += this.state.count === 0 ? "warning" : "primary";
        return classes;
    }

    handleCounter(){
        const {count} = this.state;
        return count === 0 ? 'Zero' : count;
    }
}
 
export default Counter;

I dont think i understand what you want to achieve, but if in this line

<button onClick={ () =>this.handleIncreement(product) } className="btn btn-secondary btn-sm">Increement</button>

you just want to increase the count, just do this:

<button 
  onClick={ () =>{
    this.setState(prev=>({count: prev.count +1}))
  } } 
  className="btn btn-secondary btn-sm">Increement</button>

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