带有Typescript和React Hooks的多个已检查项目

问题描述

我已经为此努力了一段时间,无法弄清。

我已经复制了Internet上的一些解决方案,但没有一个起作用。

我有这个代码的父组件

const [
  solutionsSelectedForPublishing,setSolutionsSelectedForPublishing,] = useState<Array<string>>([]);

...

const handleRowSelectionClick = (e: any) => {
  const newState = [...solutionsSelectedForPublishing];
  if (e.target.checked) {
    newState.push(e.target.value);
  } else {
    newState.filter((prev) => prev !== e.target.value);
  }
  setSolutionsSelectedForPublishing(newState);
};

以及子组件

<input
  type="checkBox"
  value={cell.row.allCells[0].value}
  onClick={handleRowSelectionClick}
/>;

我遇到的问题是,添加到solutionsSelectedForPublishing数组中的项不会持续存在。仅出现一次,当我单击另一个检查输入时,它将替换该项目,而不是将其添加到数组中。我不明白为什么,我尝试了很多事情...

解决方法

我找到了解决方案。就像魅力一样

setSolutionsSelectedForPublishing((solutionsSelectedForPublishing) => [
  ...solutionsSelectedForPublishing,...newState,]);