javascript 如何用一个变量数组来做一个检查表?

vbkedwbf  于 2022-11-20  发布在  Java
关注(0)|答案(1)|浏览(131)

我想建立一个自我更新的过滤器与复选框:

//extract tags to new array
const tags = [...new Set(shooting.map(({ tag }) => tag).flat(1))];
//  result: tags = ['wedding', 'couple', 'NSWF']  // <- here undefinded count of tags !

function Test() {
  return (
      <FilterCheckboxBar
       filteredTags={tags} />
  );}
export default Test;

筛选器复选框栏:

interface Filter {
  filteredTags: any;
}

function FilterCheckboxBar(props: Filter) {

  const [values, setValues] = useState<any>([]);   // <- I guess here is something missing

  //  ----- Handle Checkbox-----                   // <- or in this one is an error
  const handleChange = (e: any) => {
    setValues((prevState: any) => {
      const [name] = e.target;
      return {
        ...prevState,
        [name]: !prevState[name],
      };
    });
  };

  return (
    <div className="filterbar">

  {/* this list my checkboxes  */}
      {props.filteredTags.map((list: any, i: any) => (
        <label key={i} htmlFor={list}>
          <input
            className="checkbox"
            type="checkbox"
            name={list}
            id={list}
            onChange={(e) =>handleChange(e)}
            checked={values}
          />
          {list}
        </label>
      ))}
    </div>
  );
}

export default FilterCheckboxBar;

通过点击一个复选框,我的页面变白色,在控制台这个消息来:未捕获的类型错误:对象不可迭代(无法读取属性Symbol(Symbol.iterator))
我想我必须用useState做一些事情,但不知道,如何建立这个。

klr1opcd

klr1opcd1#

您可以执行以下操作:

function FilterCheckboxBar(props: Filter) {
  const [values, setValues] = useState<any>(props.filteredTags.reduce((a, c) => (a[c] = false, a), {}));

  ..

  return (
    <div className="filterbar">
      {values.map((list: any, i: any) => (
        ..
      ))}
    </div>
  );
}

export default FilterCheckboxBar;

此外,它应该是const { name } = e.target;,而不是const [name] = e.target;

相关问题