循环通过响应设置状态

时间:2016-12-01 14:57:12

标签: javascript reactjs ecmascript-6

我有一个事件处理程序在响应中设置10个项目的状态,最好的方法是设置它而不重复this.state。

handleOpacityThermatic(event) {
    if (event == 0.1) { this.setState({ opacityValue: 0.1, opacityName: '10%' }); }
    if (event == 0.2) { this.setState({ opacityValue: 0.2, opacityName: '20%' }); }
    if (event == 0.3) { this.setState({ opacityValue: 0.3, opacityName: '30%' }); }
    if (event == 0.4) { this.setState({ opacityValue: 0.4, opacityName: '40%' }); }
    if (event == 0.5) { this.setState({ opacityValue: 0.5, opacityName: '50%' }); }
    if (event == 0.6) { this.setState({ opacityValue: 0.6, opacityName: '60%' }); }
    if (event == 0.7) { this.setState({ opacityValue: 0.7, opacityName: '70%' }); }
    if (event == 0.8) { this.setState({ opacityValue: 0.8, opacityName: '80%' }); }
    if (event == 0.9) { this.setState({ opacityValue: 0.9, opacityName: '90%' }); }
    if (event == 1.0) { this.setState({ opacityValue: 1.0, opacityName: '100%' }); }

},

for循环呢?

 for (let i = 1; i <= 10; i++) {
}

1 个答案:

答案 0 :(得分:3)

使用事件的值。

const eventValues = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0];

handleOpacityThermatic(event) {
   if (eventValues.includes(Number(event)) {
       this.setState({ opacityValue: event, opacityName: event*100 + '%' }); 
   }
},

或使用字符串插值

handleOpacityThermatic(event) {
  if (eventValues.includes(Number(event)) {
     this.setState({ opacityValue: event, opacityName: `${event*100}%` });
  }
},

感谢kjonsson&amp;安德鲁李的善意提醒。