reactjs - 无法使用子元素中的复选框读取未定义的属性“数据”
问题描述
我从列表中生成子元素,因此每个子元素都有相同的复选框。然后我想创建一个检查复选框状态的函数(handleChecked)
但我得到这个错误
无法读取未定义的属性“数据”
这是我的情况的一个例子: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;
推荐阅读
- sql-server - 在 T-SQL 中使用 CAST 将 NVARCHAR 转换为 Float 时出错
- javascript - 单击按钮时从 GET 方法获取对象列表并插入 html 页表
- c++ - 如何从 C++ 中的继承类更改存储在父类中的变量
- scala - 如何在 spark executor 收集所有记录并将其作为批处理
- python - Python - 如果值符合条件,则打印字典元素
- azure-data-explorer - Azure 数据资源管理器限制
- python - 使用字符串格式化时出现 TypeError
- log4j2 - 如何为 log4j2 自定义 GELF 附加程序?
- ios - 从编码教育应用程序中识别 Swift 语法
- r - 如何绘制 ggplot 树图?