typescript 更新复选框组组件的状态不会记录新状态

pkbketx9  于 2023-02-17  发布在  TypeScript
关注(0)|答案(1)|浏览(129)

这是一个用Storybook编写的复选框组组件,这个组可以包含多个复选框选项,允许多选,它接受一个可选的属性,这个属性是一个布尔值数组,叫做options,它包含了复选框的原始值。
例如,如果组中有3个复选框,并且数组为[true, false, false],则表示最初选中了第一个复选框,而未选中其他复选框。
它看起来工作正常,问题是当状态更新时,阵列应该修改其值,我添加了一个console.log,但它根本没有记录。
下面是代码:

    • 复选框-组.故事. tsx**
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { useState } from 'react';

import { CheckboxGroup } from './checkbox-group';
import { CheckboxGroupItem } from './checkbox-group-item';
import { StorybookCheckboxGroupSetupProps } from './checkbox-group.types';

const options = [
  {
    label: 'first',
    value: 'Chocolate',
    name: 'selection-box',
  },
  {
    label: 'second',
    value: 'Candy',
    name: 'selection-box',
  },
  {
    label: 'third',
    value: 'Lollipop',
    name: 'selection-box',
  },
];

export default {
  title: 'Molecules/CheckboxGroup',
  component: CheckboxGroup,
  parameters: {},
  args: {},
  argTypes: {},
} as ComponentMeta<typeof CheckboxGroup>;

const CheckboxGroupSetup = ({
  handleCheckboxOnChange,
  currentOption,
}: StorybookCheckboxGroupSetupProps) => {
  return (
    <CheckboxGroup>
      {options.map((option, index) => {
        return (
          <CheckboxGroupItem
            key={option.label}
            option={option}
            defaultChecked={currentOption[index]}
            onChange={handleCheckboxOnChange}
          />
        );
      })}
    </CheckboxGroup>
  );
};

const useControlledCheckboxGroup = (initialValues: Array<boolean> = [true, false, true]) => {
  const [currentOption, setCurrentOption] = useState<Array<boolean>>(initialValues);

  const handleCheckboxOnChange = (position: number) => {
    const updatedCheckedState = initialValues.map((item, index) =>
      index === position ? !item : item
    );
    console.log('updatedCheckedState: ', updatedCheckedState); // <- NOTHING LOGGED!
    setCurrentOption(updatedCheckedState);
    console.log('currentOption: ', currentOption); // <- NOTHING LOGGED!
  };

  return { currentOption, handleCheckboxOnChange };
};

export const radioGroup: ComponentStory<typeof CheckboxGroup> = () => {
  const { currentOption, handleCheckboxOnChange } = useControlledCheckboxGroup();

  return (
    <CheckboxGroupSetup
      currentOption={currentOption}
      handleCheckboxOnChange={handleCheckboxOnChange}
    />
  );
};
    • 复选框-组. tsx**
import { Fragment } from 'react';

import { CheckboxGroupProps } from './checkbox-group.types';

export const CheckboxGroup = ({ children }: CheckboxGroupProps) => {
  return <Fragment>{children}</Fragment>;
};
    • 复选框组项目. tsx**
import {
  SelectionBoxCheckbox,
  CheckboxGroupOption,
  CheckboxGroupLabel,
} from './checkbox-group.styles';
import { CheckboxGroupItemProps } from './checkbox-group.types';

export const CheckboxGroupItem = ({ option, onChange, ...rest }: CheckboxGroupItemProps) => {
  return (
    <CheckboxGroupOption>
      <CheckboxGroupLabel htmlFor={option.label}>
        <SelectionBoxCheckbox
          type="checkbox"
          name={option.name}
          value={option.value}
          id={option.label}
          onChange={() => onChange}
          {...rest}
        />
        {option.value}
      </CheckboxGroupLabel>
    </CheckboxGroupOption>
  );
};
    • 复选框-组.类型. ts**
import { ReactNode } from 'react';

export interface CheckboxGroupProps {
  errorMessage?: string;
  children: ReactNode;
  isError?: boolean;
  defaultChecked?: boolean | undefined;
  onChange?: (position: number) => void;
}

export interface CheckboxGroupItemProps {
  errorMessage?: string;
  isError?: boolean;
  defaultChecked?: boolean | undefined;
  onChange?: (position: number) => void;
  option: {
    name: string;
    value: string;
    label: string;
  };
}

export interface StorybookCheckboxGroupSetupProps {
  errorMessage?: string;
  handleCheckboxOnChange?: (position: number) => void;
  currentOption: Array<boolean>;
  areRadiosDisabled?: boolean;
}

还在此处添加了样式化组件,甚至认为它们对问题并不重要:

    • 复选框-组.样式. ts**
import styled from 'styled-components';
import { darkColors } from 'config';
export const StyledFieldSet = styled.fieldset`
  border: none;
`;

export const SelectionBoxCheckbox = styled.input`
  cursor: pointer;
  margin-right: 1rem;
  &:checked {
    background-color: red;
    border-color: orange;
  }
`;

export const CheckboxGroupLabel = styled.label`
  background-color: ${darkColors.background.main};
  display: flex;
  width: 100%;
  margin: 1.8rem;
  color: ${({ theme }) => theme.colors.grey[100]};
  font-size: ${({ theme }) => theme.fonts.sizes.default};
  font-weight: ${({ theme }) => theme.fonts.weight.regular};
  font-family: ${({ theme }) => theme.fonts.familySansPro};
  line-height: 2rem;
  cursor: pointer;
  width: 63.6rem;
  border: solid 0.1rem ${({ theme }) => theme.colors.grey[1000]};
  border-radius: 0.5rem;
  padding: 1.8rem;
  &:hover {
    border-color: ${({ theme }) => theme.colors.grey[400]};
  }
  &:focus {
    border-color: ${darkColors.info.main};
  }
`;

export const CheckboxGroupOption = styled.fieldset`
  display: flex;
  flex-direction: row;
  border: none;
`;

出什么事了吗?

y1aodyip

y1aodyip1#

您似乎没有调用onChange()
() => onChange替换为() => onChange()

相关问题