繁体   English   中英

如何在 ReactJS 中重新渲染回调 function?

[英]How to re-render a callback function in ReactJS?

我正在通过复选框制作过滤器 function。 我做了一个像下面这样的复制。 我更改了数组中的值,但复选框选中的状态没有改变,我错过了什么? 我想我必须重新渲染list ,但它也将检查数组重新填充到初始 state。 我应该怎么办? 谢谢!

import * as React from "react";
import "./styles.css";
import { Checkbox } from "antd";

const arr = [
  {
    name: "haha"
  },
  {
    name: "haha2"
  },
  {
    name: "hahaha"
  }
];

const App = () => {
  let [viewAll, setViewAll] = React.useState(true);
  let checked = new Array(3).fill(true);

  // render calendars checkbox
  let list = arr.map((value, index) => {
    return (
        <Checkbox
          style={{ color: "white" }}
          checked={checked[index]}
          onChange={() => handleFilter(value, index)}
          className="check-box"
        >
          haha
        </Checkbox>
    );
  });

  const handleViewAll = () => {
    setViewAll(!viewAll);
    checked = checked.map(() => viewAll);
  };
  const handleFilter = (value, index) => {
    setViewAll(false);
    checked.map((_value, _index) => {
      if (_index === index) {
        return (checked[_index] = !checked[_index]);
      } else {
        return checked[_index];
      }
    });
    console.log(checked);
  };

  return (
    <div className="App">
      <Checkbox checked={viewAll} onChange={() => handleViewAll()}>Check all</Checkbox>
      {list}
    </div>
  );
};

export default App;

这是codesanboxlink

您应该创建checked的 state。 检查下面的代码。

let [viewAll, setViewAll] = React.useState(true);
let [checked, setChecked] = React.useState([true, true, true]);

  // render calendars checkbox
  let list = arr.map((value, index) => {
    return (
      <Checkbox
        style={{ color: "black" }}
        checked={checked[index]}
        onChange={() => handleFilter(value, index)}
        className="check-box"
      >
        {value.name}
      </Checkbox>
    );
  });

  const handleViewAll = () => {
    setViewAll(!viewAll);
    setChecked(() => checked.map(item => !viewAll));
  };
  const handleFilter = (value, index) => {
    setViewAll(false);
    setChecked(() =>
      checked.map((_value, _index) => {
        if (_index === index) return !checked[_index];
        return checked[_index];
      })
    );
  };

  return (
    <div className="App">
      <Checkbox checked={viewAll} onChange={() => handleViewAll()}>
        {checked}
      </Checkbox>
      {list}
    </div>
  );

代码沙盒演示

您必须将checked数组定义为state值。

现在你的代码没有触发render function 因为checked的数组不是props但也不是state

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM