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

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


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


白猪掌柜的
浏览 73回答 2
2回答

蝴蝶刀刀

您应该创建checked状态。检查下面的代码。let [viewAll, setViewAll] = React.useState(true);let [checked, setChecked] = React.useState([true, true, true]);&nbsp; // render calendars checkbox&nbsp; let list = arr.map((value, index) => {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <Checkbox&nbsp; &nbsp; &nbsp; &nbsp; style={{ color: "black" }}&nbsp; &nbsp; &nbsp; &nbsp; checked={checked[index]}&nbsp; &nbsp; &nbsp; &nbsp; onChange={() => handleFilter(value, index)}&nbsp; &nbsp; &nbsp; &nbsp; className="check-box"&nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; {value.name}&nbsp; &nbsp; &nbsp; </Checkbox>&nbsp; &nbsp; );&nbsp; });&nbsp; const handleViewAll = () => {&nbsp; &nbsp; setViewAll(!viewAll);&nbsp; &nbsp; setChecked(() => checked.map(item => !viewAll));&nbsp; };&nbsp; const handleFilter = (value, index) => {&nbsp; &nbsp; setViewAll(false);&nbsp; &nbsp; setChecked(() =>&nbsp; &nbsp; &nbsp; checked.map((_value, _index) => {&nbsp; &nbsp; &nbsp; &nbsp; if (_index === index) return !checked[_index];&nbsp; &nbsp; &nbsp; &nbsp; return checked[_index];&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; );&nbsp; };&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <Checkbox checked={viewAll} onChange={() => handleViewAll()}>&nbsp; &nbsp; &nbsp; &nbsp; {checked}&nbsp; &nbsp; &nbsp; </Checkbox>&nbsp; &nbsp; &nbsp; {list}&nbsp; &nbsp; </div>&nbsp; );代码沙盒演示

慕勒3428872

您必须将checked数组定义为一个state值。现在你的代码没有触发render函数,因为checked数组不是props但也不是state。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript