我有这个代码:
const getElementDims = (node, id) => {
this.setState(
taskDims[id] = node.getBoundingClientRect()
)
}
我知道这段代码不起作用,但我真的不知道如何解决这个问题。我想将状态的 taskDims
对象的键设置为从函数中获取的 id,并将节点的参数设置给它。问题出在 key 上。我该如何设置它?将其转换为数组,并将数组的元素设置为对象,并设置id的键值对是不是更好的解决方案?
最佳答案
您可以创建 taskDims
对象的副本并使用键 id
覆盖该值:
const getElementDims = (node, id) => {
this.setState(previousState => {
const taskDims = {...previousState.taskDims};
taskDims[id] = node.getBoundingClientRect();
return { taskDims };
});
}
关于javascript - 如何从函数的参数设置状态键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51350626/