javascript - [tag][React.js] 孩子展示道具未定义
问题描述
我刚开始学习 React js,并且正在关注 youtube 上的 mosh 教程。我很肯定我做了他所做的,但我的道具说未定义。
counters.jsx 中的“值”是可访问的,但是当我尝试获取 id 时,它显示未定义。这是我在控制台中得到的输出:“ Event handler called! undefined ”
计数器.jsx
import React, { Component } from "react";
import Counter from "./counter";
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
],
};
handleDelete = (counterID) => {
console.log("Event handler called!", counterID);
};
render() {
return (
<div>
{this.state.counters.map((counter) => (
<Counter
key={counter.id}
onDelete={this.handleDelete}
value={counter.value}
/>
))}
</div>
);
}
}
export default Counters;
计数器.jsx
import React, { Component } from "react";
class Counter extends Component {
state = {
value: this.props.value,
};
// constructor() {
// super();
// this.handleIncrement = this.handleIncrement.bind(this);
// }
handleIncrement = () => {
this.setState({ value: this.state.value + 1 });
};
render() {
return (
<div>
<span className={this.getBadgeClasse()}>{this.formatCount()}</span>
<button
onClick={() => this.handleIncrement(this.state.product)}
className="btn btn-secondary btn-sm"
>
Increment
</button>
<button
onClick={() => this.props.onDelete(this.props.id)}
className="btn btn-danger btn-sm m2"
>
Delete
</button>
</div>
);
}
getBadgeClasse() {
let classes = "badge m-2 badge-";
classes += this.state.value === 0 ? "warning" : "primary";
return classes;
}
formatCount() {
const { value: count } = this.state;
return count === 0 ? "Zero" : count;
}
}
export default Counter;
谢谢你
解决方案
在 te Counters.jsx 中,您不传递 id 道具。你必须这样:
{this.state.counters.map((counter) => (
<Counter
key={counter.id}
id={counter.id}
onDelete={this.handleDelete}
value={counter.value}
/>
))}
推荐阅读
- python - 在 python 和 Matlab 之间通过 TCP 套接字传输数据
- javascript - 如何将 jQuery 函数(监视 css 类)转换为 Vue 3 中的可用代码?
- swift - SwiftUI 视图转换匹配分段选择器
- python - 打印熊猫数据框时如何在行之间添加下划线分隔符?
- reactjs - 如何渲染属性位于嵌套对象数组中的元素数组?
- vuejs2 - 启动服务器后,我在 vuejs 中遇到以下问题
- spring-boot - 如何传递lookuptype!在 java 中使用 GraphQLTemplate 时枚举
- firebase - 直接来自 Firebase 存储的 Steam 音频文件
- c# - 在 C# 中从类中打印一个数组
- html - 说明框未正确呈现