Cannot read property 'data' of undefined with checkboxs in Child elements

。_饼干妹妹 提交于 2020-07-09 12:15:12

问题


I generate child elements from a list, so each child has the same checkboxes. Then I want to create a function that checks the status of my checkboxs (handleChecked)

but i get this error

Cannot read property 'data' of undefined

here is an exemple of my situation : https://codesandbox.io/s/test-uz-713xy


回答1:


You can do the below changes. You will be getting the logs printed while toggling the state. You can store the function invariable and than call it as I have demonstrated below

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;



回答2:


I assume this example isn't your code because it seems to be working fine.

From the error I am assuming you are accessing your state in a wrong way. You are getting state as undefined. Can you share the code where you access data from the state?



来源:https://stackoverflow.com/questions/62773830/cannot-read-property-data-of-undefined-with-checkboxs-in-child-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!