首页 > 解决方案 > 无法使用子元素中的复选框读取未定义的属性“数据”

问题描述

我从列表中生成子元素,因此每个子元素都有相同的复选框。然后我想创建一个检查复选框状态的函数(handleChecked)

但我得到这个错误

无法读取未定义的属性“数据”

这是我的情况的一个例子:https ://codesandbox.io/s/test-uz-713xy

标签: reactjscheckboxparent-child

解决方案


您可以进行以下更改。您将在切换状态时打印日志。您可以将函数存储为不变,然后像我在下面演示的那样调用它

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

class Profils extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [
        {
          name: "Perceval"
        },
        {
          name: "Merlin"
        },
        {
          name: "General Kenobi"
        }
      ]
    };

    this.handleChecked = this.handleChecked.bind(this);
  }

  handleChecked(event) {
    if (event.target.checked === true) {
      console.log(event.target.id, " is checked");
    } else if (event.target.checked === false) {
      console.log(event.target.id, " is unchecked");
    } else {
      console.log("test fail");
    }
  }

  render() {
    let ch = this.handleChecked;
    return (
      <div className="Profil">
        {this.state.data.map(function(panel) {
          return (
            <div key={panel.name}>
              <h1> Hello my name is {panel.name}</h1>
              <input
                className="tgl tgl-skewed"
                id={panel.name}
                type="checkbox"
                onChange={(e)=>ch(e)}
              />
              <label
                className="tgl-btn"
                data-tg-off="Test is OFF"
                data-tg-on="Test is ON"
                htmlFor={panel.name}
              />
            </div>
          );
        })}
      </div>
    );
  }
}

export default Profils;

推荐阅读