【问题标题】:Multiple and Multi selected Checkboxes in ReactJSReactJS 中的多选和多选复选框
【发布时间】:2020-05-20 10:18:06
【问题描述】:

所以我开始以一种非常困难的方式学习 React。

我只是偶然发现了一个问题:

复选框。

逻辑应该是这样的(只是它应该如何工作的一个快速示例):

如果选择了None,则无法选择01 到05,则所有内容都被禁用,并且所有内容都应更新端点。

https://codepen.io/lockeag/pen/NWGexXv(此示例有一个流程,它将启用 None 并取消选中任何复选框,它应该启用 None 而没有选中其他复选框,但它将作为示例)

该示例使用 DOM 来确保选中复选框,但在 React 中我们有状态,我想了解更多。

这是我的第一个练习(甚至没有保存在数据库中):

import React, { useState, useEffect, Suspense } from 'react'
import {ApiUrl} from '../../utils/ApiUrl'
import { getToken } from '../../utils/Auth'
import { Row, Col, Card, CardBody, Form, FormGroup, Label, Input, Button, Table, CustomInput, Container } from 'reactstrap';
import axios from 'axios'
import { useHistory } from "react-router-dom";

export default function EditSheet(props) {

const getSheet = () => {

        const config = {
          headers: { Authorization: `Bearer ${getToken()}` }
        };

        axios.get(`${Url}/sheets/${props.id}`, config)
        .then(res => {
            if(res.data.sheet.Aht){
                setAht(res.data.sheet.Aht)
            }
            else{
                setAht('')
            }

            setLoading(false)
        })
        .catch(console.error);
}

 const onSubmitSheet = e =>{
        e.preventDefault() 
        const newData = {
            "Aht": Aht,

        }

        editSheet(newData)

} 

    const editSheet = async(sheetData) => {
        const myHeaders = new Headers();
        myHeaders.append("Authorization", `Bearer ${getToken()}`);
        myHeaders.append("Content-Type", "application/json");

        const raw = JSON.stringify(sheetData);

        const requestOptions = {
        method: 'PUT',
        headers: myHeaders,
        body: raw,
        redirect: 'follow'
        };

        fetch(`${Url}/sheets/${props.id}`, requestOptions)
        .then(response => response.json())
        .then(result => {
            if(result.status === "ok"){
                history.push("/dashboard/sheets");
            }
        })
        .catch(error => console.error(`Erro: ${error}`));

    };


const [Aht, setAht] = useState({
    num: '',
    isChecked: false
})

const handleInputChangeHipe = (e) => {
    const target = e.target
    let numVal = parseInt(target.value)
    const arr = [...Aht]
    const newArr = arr.filter(item => item !== numVal)
    const value = target.type === "checkbox" ? target.checked : target.value;

    if(target.checked){
        setAht({
            ...Aht,
            num: numVal,
            [target.name]: value
        })

        console.log(`${numVal} is ${value}. should be added.`);

    } else {

        console.log(newArr)
        setAht({
            ...Aht,
            num: newArr,
            [target.name]: value
        })
        console.log(`${numVal} is ${value}. will not be added.`);

    }
}

 return (
        <>
        <div className="content">
                        <Container fluid>
                            <Suspense>
                                {
                                loading ?
                                <h5>Cargando...</h5> :
                                <>
                                <Form onSubmit={onSubmitSheet} method="post">
                                    <FormGroup>

                                    <Label for="exampleCheckbox">Aht</Label>                                                   
                                    <div>
                                        <CustomInput 
                                        id="hiper0" 
                                        type="checkbox" 
                                        label="None" 
                                        value="0" 
                                        checked={Aht.isChecked} 
                                        onChange={handleInputChangeHipe} 
                                        /> 
                                        <CustomInput 
                                        id="hiper1" 
                                        type="checkbox" 
                                        label="One" 
                                        value="1" 
                                        onChange={handleInputChangeHipe} 
                                        checked={Aht.isChecked} /> 
                                        <CustomInput 
                                        id="hiper2" 
                                        type="checkbox" 
                                        label="Two" 
                                        value="2" 
                                        onChange={handleInputChangeHipe} 
                                        checked={Aht.isChecked} />
                                        <CustomInput 
                                        id="hiper3" 
                                        type="checkbox" 
                                        label="Three" 
                                        value="3" 
                                        onChange={handleInputChangeHipe} 
                                        checked={Aht.isChecked}/>
                                        <CustomInput 
                                        id="hiper4" 
                                        type="checkbox" 
                                        label="Four" 
                                        value="4" 
                                        onChange={handleInputChangeHipe} 
                                        checked={Aht.isChecked}/>
                                        <CustomInput 
                                        id="hiper5" 
                                        type="checkbox" 
                                        label="Others" 
                                        value="5" 
                                        onChange={handleInputChangeHipe} 
                                        checked={Aht.isChecked}/>
                                    </div>
                                    </FormGroup>
                                    </Form>
                                </>
                                }
                            </Suspense>
                        </Container>
        </div>
        </>
    )
}

上面的这个练习只是为了了解一切是如何工作的,我如何检查状态,以及保存和编辑到端点。

但正如你所想象的那样充满了流动

我的问题

  • 首先我必须使用 Axios,因为 Fetch 不允许我获取端点,但 Fetch 允许我编辑 (????)
  • 每次我取消选中我都会收到 TypeError:
Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

但如果我更改 React.UseState 并将函数作为数组调用,它也将适用于我真正希望更改的 DOM 流:

const [Aht, setAht] = useState('')

const handleInputChangeHipe = (e) => {
    const target = e.target
    let numVal = parseInt(target.value)
    const arr = [...Aht]
    const newArr = arr.filter(item => item !== numVal)

    if(e.target.value !=0 && e.target.checked){
        document.getElementById("hiper0").disabled = true
        document.getElementById("hiper0").checked = false
    }else{
        document.getElementById("hiper0").disabled = false
    }

    if(target.checked){
        setAht([
            ...Aht,
            numVal,
        ])

        console.info(`${numVal} is ${value}. should be added.`);

    } else {
        console.log(newArr)
        setAht(AhtnewArr)

        console.info(`${numVal} is ${value}. will not be added.`);

    }

谢谢

【问题讨论】:

  • 我认为这里的问题是你还没有完全考虑 React 的方式,而且这个复杂的 UI 没有帮助。我建议你现在只删除 axios 并获取并严格处理 UI 元素的组合并让它们正确更新状态(这涉及 onChange),一旦你得到修复,那么添加 axios 应该是小菜一碟.

标签: javascript reactjs checkbox state


【解决方案1】:

在您的代码中,您的状态aht 的初始值为空字符串。 const [Aht, setAht] = useState('') 并且您试图将其传播到数组 const arr = [...Aht] 中,因此出现错误。

您需要更改代码的结构以使您的复选框(一到四个)和您的无复选框正常工作。

基本上,有一个对象作为状态并点击复选框更新状态。此外,动态启用和禁用无复选框。

代码片段

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const initialValues = {
    none: false,
    one: false,
    two: false,
    three: false
  };
  const [Aht, setAht] = useState(initialValues);

  const handleInputChangeHipe = e => {
    const target = e.target;
    setAht(prev => ({
      ...prev,
      [target.name]: target.checked ? true : false,
      none: false
    }));
  };
  const handleNone = e => {
    if (e.target.checked) {
      setAht({ ...initialValues, none: true });
    } else {
      setAht(prev => ({
        ...prev,
        none: false
      }));
    }
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      NONE{" "}
      <input
        onChange={handleNone}
        name="none"
        type="checkbox"
        label="none"
        checked={Aht.none}
      />
      <br />
      one{" "}
      <input
        onChange={handleInputChangeHipe}
        name="one"
        type="checkbox"
        label="one"
        disabled={Aht.none}
        checked={Aht.one}
      />
      <br />
      two{" "}
      <input
        onChange={handleInputChangeHipe}
        name="two"
        type="checkbox"
        disabled={Aht.none}
        label="two"
        checked={Aht.two}
      />
      <br />
      three{" "}
      <input
        onChange={handleInputChangeHipe}
        name="three"
        type="checkbox"
        disabled={Aht.none}
        label="one"
        checked={Aht.three}
      />
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 2016-12-30
    • 2019-10-13
    • 2019-02-13
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多