通过动态变量检索React状态值

时间:2018-02-26 08:10:25

标签: javascript reactjs

我正在构建一个简单的rgba选择器,允许用户通过向上箭头和向下箭头键切换各个值。下面是我的代码片段。

class App extends Component {
  constructor(){
  super();
  this.state = {
   red: 0,
   green: 200,
   blue: 0,
   opacity: 1,
};
this.handleValueChange = this.handleValueChange.bind(this);
this.handleArrowKeysInput = this.handleArrowKeysInput.bind(this);

// for using up and down arrows to adjust the values
    handleArrowKeysInput = e => {
    const keyPressed = e.keyCode;
    let {id} = e.target;
    console.log(id); //returns red OR green OR blue
    console.log(this.state.id);

    // if up button is pressed
    if(keyPressed === 38){
      // if value is already 255, stop increment
      if(this.state.green >= 255) return;
      console.log(`up button is pressed`);
      this.setState({[id]: this.state.id + 1});
    }

    // if down button is pressed 
    else if(keyPressed === 40){
      // if value is already 0, stop decrement
      if(this.state.id <= 0) return;
      console.log(`down button is pressed`);
      this.setState({[id]: this.state.id - 1});
    }
  }

<input value={this.state.red} type="text" id="red" onChange= {this.handleValueChange} onKeyDown={this.handleArrowKeysInput}/>

console.log(id)会返回所需的红色或绿色或蓝色值。

然而,当我尝试console.log(this.state.id)时。它显示undefined

为什么会这样?

1 个答案:

答案 0 :(得分:1)

因为你的状态对象中没有'id'属性。相反,你应该首先检查id的值来设置状态,然后例如如果它是'red',你可以调用setState({red: this.state.red - 1})

以下是我的意思的更明确的例子:

if(keyPressed === 38){
    switch (id) {
        case "red":
            if(this.state.red >= 255) return;
            this.setState({red: this.state.red + 1});
        break;
        case "green":
            if(this.state.green >= 255) return;
            this.setState({green: this.state.green + 1});
        break;
        case "blue":
            if(this.state.blue >= 255) return;
            this.setState({blue: this.state.blue + 1});
        break;
    }
}