小编Nak*_*esh的帖子

如何使用React钩子实现多个复选框

我想使用react-hook在HTML页面上实现多个复选框。

我尝试使用以下URL实施:https : //medium.com/@Zh0uzi/my-concerns-with-react-hooks-6afda0acc672。在提供的链接中,它是使用类组件完成的并且可以正常工作,但是每当我使用React钩子setCheckedItems更新复选框选中状态时,它都不会重新呈现视图。

第一次渲染视图,并且从Checkbox组件打印console.log()。单击复选框功能后,将调用handleChange,并且checkedItems更新该值,但视图不会再次呈现(不打印console.log())。并且{checkedItems.get(“ check-box-1”)}也不打印任何值。

以下是我的示例代码。

复选框示例

import React, { useState } from 'react';
import Checkbox from '../helper/Checkbox';

const CheckboxExample = () => {
    const [checkedItems, setCheckedItems] = useState(new Map());

    const handleChange = (event) => {
        setCheckedItems(checkedItems => checkedItems.set(event.target.name, event.target.checked));
        console.log("checkedItems: ", checkedItems);
    }

    const checkboxes = [
        {
            name: 'check-box-1',
            key: 'checkBox1',
            label: 'Check Box 1',
        },
        {
            name: 'check-box-2',
            key: 'checkBox2',
            label: 'Check Box 2',
        } …
Run Code Online (Sandbox Code Playgroud)

javascript checkbox reactjs react-hooks

3
推荐指数
2
解决办法
3906
查看次数

标签 统计

checkbox ×1

javascript ×1

react-hooks ×1

reactjs ×1