无法读取 属性 'data' of undefined with checkboxes in Child elements
Cannot read property 'data' of undefined with checkboxs in Child elements
我从列表中生成子元素,因此每个子元素都有相同的复选框。
然后我想创建一个函数来检查我的复选框的状态 (handleChecked)
但是我收到这个错误
Cannot read property 'data' of undefined
这是我的情况的一个例子:https://codesandbox.io/s/test-uz-713xy
您可以进行以下更改。您将在切换状态时打印日志。您可以存储函数不变,而不是像我在下面演示的那样调用它
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;
我假设此示例不是您的代码,因为它似乎工作正常。
根据错误,我假设您正在以错误的方式访问您的状态。您正在获得未定义的状态。你能分享你从州访问数据的代码吗?
我从列表中生成子元素,因此每个子元素都有相同的复选框。 然后我想创建一个函数来检查我的复选框的状态 (handleChecked)
但是我收到这个错误
Cannot read property 'data' of undefined
这是我的情况的一个例子:https://codesandbox.io/s/test-uz-713xy
您可以进行以下更改。您将在切换状态时打印日志。您可以存储函数不变,而不是像我在下面演示的那样调用它
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;
我假设此示例不是您的代码,因为它似乎工作正常。
根据错误,我假设您正在以错误的方式访问您的状态。您正在获得未定义的状态。你能分享你从州访问数据的代码吗?