问题
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