gpt4 book ai didi

javascript - React,使用目标名称和值从 map 更新状态函数

转载 作者:行者123 更新时间:2023-12-01 00:21:06 25 4
gpt4 key购买 nike

我正在尝试更新状态,当前的 func (handleLabelChange) 理论上可以工作(更新状态),但我想添加名称而不是 textOne 和值 ”??? ?" 动态地从文本区域字段或任何其他字段。某种 target.name 和 target.value,但我不知道如何处理它。

handleLabelChange = id => {
const updatedItems = this.state.items.map(item => {
if (item.id === id) {
return {
...item,
textOne: "????" // grab textarea name and value here
};
} else {
return item;
}
});

this.setState({
items: updatedItems
});

};

JSX 内部 map 函数:

{this.state.items.map(el => (

<textarea rows="5" placeholder="Text here..." name="textOne" onChange={() => this.handleLabelChange(el.id)}></textarea>

}

最佳答案

我会在文本区域上做这样的事情:

onChange={this.handleLabelChange(el.id, 'name')}

其中第二个参数是属性,然后handleLabelChange看起来像这样

function handleLabelChange(id, property) {
return ev => {
const newVal = ev.target.value;

const updatedItems = this.state.items.map(item => {
if (item.id === id) {
const newItem = Object.assign({}, item);
newItem[property] = newVal;
return newItem;
} else {
return item;
}
});

this.setState({
items: updatedItems
});
}
}

您的handleLabelChange返回回调函数,而不是本身回调函数

关于javascript - React,使用目标名称和值从 map 更新状态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59423020/

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