为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

白猪掌柜的 2022-10-13 16:18:22
我正在通过复选框制作过滤功能。我做了一个像下面这样的复制。我更改了数组中的值,但复选框选中的状态没有改变,我错过了什么?我想我必须重新渲染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
查看完整描述

2 回答

?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

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


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>

  );

代码沙盒演示


查看完整回答
反对 回复 2022-10-13
?
慕勒3428872

TA贡献1848条经验 获得超6个赞

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

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


查看完整回答
反对 回复 2022-10-13
  • 2 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信