Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

reactjs - How to select / deselect checkbox in react typescript?

I am working with checkboxes in react typescript. I am handling onChange event but it's not working properly. code for parent component -

import { myCheckboxData } from "./constant";

export const ParentComponent = (props: Test) => {
  const myCheckboxDataAPI = myCheckboxData!.map((data) => Object.assign({}, data));
  const initialData: InterfaceA = {
    myType: myCheckboxDataAPI!,
  };
  const [myInitialState, setMyInitialState] = React.useState(initialData);

  const onChange = (type: string, selectedValue: boolean) => {
    const index: number = myCheckboxDataAPI!.findIndex((x) => x.label === selectType);
    if (index > -1) {
      myCheckboxDataAPI![index].checked = !selectedValue;
      setMyInitialState({
        ...myInitialState,
        myType: myCheckboxDataAPI,
      });
    }
  };
  return <FirstChild onChange={onChange} checkboxData={myInitialState} />;
};

code for FirstChild Component -

import react from "react";

interface Test1 {
  checkboxData: Array<ICheckboxProps>;
  onChange: (type: string, value: boolean) => void;
}

export const FirstChild = (props: Test1) => {
  return (
    <Grid container wrap='nowrap'>
      {myData.map((item) => {
        return (
          <div key={`new_${item.label}`}>
            <Checkbox
              id={`new_${item.label}`}
              checked={item.checked}
              label={item.label}
              onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
                onChange(String(item.label), item.checked);
              }}
            />
          </div>
        );
      })}
    </Grid>
  );
};

myCheckboxData has 2 values in it. I am able to select both values one by one. I am also able to select/deselect a particular value. But if I want to deselect both values then it's not working. How can I make it work perfectly ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...