简体   繁体   中英

How to set max and min value for increment and decrement methods inside React

So the thing is that I'm trying to create a feedback app where users can rate the service from 1 to 10. This is an upgrade from a simple counter app, but I want to add something new into my app, the problem is that I don't know how to limit the range of max and min values. Here is my code:

 state = {
   headline: 'Please rate our service from 1 to 10',
   scale: '1: Extremly bad - 10: Extremely good',
   points: [
     { id: 1, question: 'What do you think about our food?', value: 1 },
     { id: 2, question: 'What do you think about our staff?', value: 1 },
     { id: 3, question: 'What do you think about our menu?', value: 1 },
     { id: 4, question: 'What do you think about our cleanliness?', value: 1 }
   ]
 };

 handleIncrement = point => {
   const points = [...this.state.points];
   const index = points.indexOf(point);
   points[index] = { ...point };
   points[index].value++;
   this.setState({ points });
 };

Thanks to @palaѕн I've already solved the problem. Here's the solution:

  handleIncrement = point => {
    const points = [...this.state.points];
    const index = points.indexOf(point);
    points[index] = { ...point };
    if (points[index].value < 10) {
      points[index].value++;
    }
    this.setState({ points });
  };

  handleDecrement = point => {
    const points = [...this.state.points];
    const index = points.indexOf(point);
    points[index] = { ...point };
    if (points[index].value > 1) {
      points[index].value--;
    }
    this.setState({ points });
  };

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