gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:26:09 27 4
gpt4 key购买 nike

我正在构建一个简单的 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 .

为什么会这样?

最佳答案

您的代码有点困惑,可能是因为它不是 Complete Example但我尝试为您提供一些修复它的选项。

您的初始状态构造没有id 值。

示例

this.state = {
red: 0,
green: 200,
blue: 0,
opacity: 1,
id: 0 // This should be here if you are going to use it
};

其次,您尝试将 1 添加到下面的 undefined 值;

this.setState({[id]: this.state.id + 1});

因为 this.state.idundefined,所以 this.state[id] 也将是 undefined。但是据我从你的代码中了解到你正在尝试设置 redgreenblue 值,因此你的代码应该如下所示;

this.setState({[id]: this.state[id] + 1});

因为您正试图在上述代码中获取状态值,所以使用函数式 setState 是更好的做法;

this.setState((prevState) => ({[id]: prevState[id] + 1}));

关于javascript - 通过动态变量检索 React 状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48983994/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com