首页 > 解决方案 > 反应如何使用打字稿处理复选框的选中和未选中事件

问题描述

嗨,我是 React 和打字稿的新手。我正在为复选框添加选中的属性,但发现它很棘手。我搜索了 SO,但仍然无法让它更接近工作。

这是我正在尝试做的事情:

我正在使用单个子组件创建三个复选框组件[此处显示]。它们都有自己的值,我需要动态传递。

interface ItemProps {
  readonly className?: string;
  readonly checked: boolean | undefined;
  readonly accentedUnchecked?: boolean;
  readonly imageUrl: string;
  readonly errorMessage?: string;
  readonly statusChecked?: boolean | undefined;
  readonly onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  readonly handleClick: (event: React.ChangeEvent<HTMLInputElement>) => void; 
  };

  readonly hasError?: boolean;
  readonly title?: string;
  readonly value?: number;
  readonly description?: React.ComponentType;
}
export class Item extends React.Component<
  ItemProps,
  {
    readonly isExpanded: boolean;
    readonly checkboxStatus: boolean;
    readonly temp: boolean;
    readonly checked: boolean;    
  }
> {
  constructor(props) {
    super(props);
    this.state = {
      isExpanded: false,
      checkboxStatus: false,
      temp: false,
      checked: this.state.temp
    };
    this.handleClick = this.handleClick.bind(this);
    this.onChange = this.onChange.bind(this);    
  }`

  private onChange(e: React.ChangeEvent<HTMLInputElement>) {   
    this.setState({ temp: e.currentTarget.checked });
  }

  private readonly handleClick = e =>
    this.props.onChange({
      currentTarget: { checked: e.currentTarget.checked }
    } as any);

  render() {

    const unchecked = this.props.accentedUnchecked && this.props.checked === false;

    return (

<label className="checkbox">
          <input
            type="checkbox"
            checked={this.onChange} //Not working
            onChange={this.props.onChange}
            onClick={this.handleClick}

            id={"test"}
            data-id="0"
          />
);

问题是我不确定如何设置选中的属性,基于Click。当我使用

checked={this.props.checked}

我正在检查所有复选框。或者如果我使用

checked={this.handleClick}

我收到错误消息

不能在打字稿中将 void 分配给布尔值”。

有关如何解决此问题的任何建议都将非常有帮助

提前致谢

标签: javascriptreactjseventscheckboxreact-redux

解决方案


如果你想快点,底部添加了在线演示。我重写了几乎所有这些东西。


一些注意点:

  • 由于您想重用子复选框,因此您不应该在子内部编写处理程序函数,而是将其公开给父母。
  • 两者都可以onClick - MouseEventonChange - ChangeEvent因为它是完全受控的,我们唯一需要传递的是它的 id。检查状态由父母持有。
  • 您可以根据从父母传递的道具在孩子内部编写嵌套的检查逻辑。
import * as React from "react";
import "./styles.css";

const data = [
  { id: 1, checked: 1 },
  { id: 2, checked: 0 },
  { id: 3, checked: 1 }
];

export default function App() {
  const [checkedList, setCheckedList] = React.useState(
    data.map(x => !!x.checked)
  );
  const onChangeHandler = (
    e: React.ChangeEvent<HTMLInputElement>,
    id: number
  ) => {
    const list = [...checkedList];
    list.splice(id - 1, 1, !list[id - 1]);
    setCheckedList(list);
  };
  return (
    <div className="App">
      <h1>Checkboxes</h1>
      {data.map((item, idx) => (
        <InsuranceItem
          id={item.id}
          key={item.id}
          checked={checkedList[idx]}
          onChange={onChangeHandler}
        />
      ))}
    </div>
  );
}

interface InsuranceItemProps {
  readonly id?: number;
  readonly className?: string;
  readonly checked: boolean | undefined;
  readonly accentedUnchecked?: boolean;
  readonly imageUrl?: string;
  readonly errorMessage?: string;
  readonly statusChecked?: boolean | undefined;
  readonly onChange: (
    event: React.ChangeEvent<HTMLInputElement>,
    id: number
  ) => void;
  // readonly handleClick: (event: React.ChangeEvent<HTMLInputElement>) => void;
  readonly hasError?: boolean;
  readonly title?: string;
  readonly value?: number;
  readonly description?: React.ComponentType;
}
class InsuranceItem extends React.Component<
  InsuranceItemProps,
  {
    // readonly isExpanded: boolean;
    // readonly checkboxStatus: boolean;
    // readonly temp: boolean;
    // readonly checked: boolean;
  }
> {
  constructor(props: InsuranceItemProps) {
    super(props);
    this.state = {
      // isExpanded: false,
      // checkboxStatus: false,
      // checked: false
    };
  }

  render() {
    const { id = 0, accentedUnchecked, checked, onChange } = this.props;
    // const unchecked = accentedUnchecked && checked === false;

    return (
      <label className="checkbox">
        <input
          type="checkbox"
          checked={checked}
          onChange={e => onChange(e, id)}
          id={id.toString()}
          data-id="0"
        />
      </label>
    );
  }
}

在此处输入图像描述

编辑警惕-http-zrbx5


推荐阅读