我正在学习CodewithMosh的课程,在此过程中,我会在单击时启动一个函数,然后该函数将ID传递给另一个组件。这将返回未定义。我尝试传递不同的值,但效果很好。我不明白这是什么问题或不同之处。
class Counters extends Component {
state = {
counters: [
{id: 1, value: 4},
{id: 2, value: 1},
{id: 3, value: 2},
{id: 4, value: 3}
]
};
handleDelete = (counterId) => {
console.log('Event Handler Called', counterId); //Function receiving data
};
render() {
return (
<div className="main">
{ this.state.counters.map(counter =>
<Counter key={counter.id} onDelete={this.handleDelete} value={counter.value}>
<h4>Counter #{counter.id}</h4>
</Counter>)}
</div>
);
}
class Counter extends Component {
state = {
value: this.props.value
}
getBadgeClasses() {
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;
}
handleIncrement = () => {
this.setState({value: this.state.value + 1});
}
render() {
return (
<div>
{this.props.children}
<span style={this.styles} className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button onClick={this.handleIncrement } className={"btn btn-secondary btn-sm"}>Increment</button>
<button
onClick={() => this.props.onDelete(this.props.id)} //The ID I'm trying to pass.
className={'btn btn-danger btn-sm m-2'}>
Delete
</button>
</div>
);
}
答案 0 :(得分:0)
您还没有在Counter组件内调用构造函数render方法,并将道具传递给它。这样做;
class Counter extends Component {
constructor(props){
super(props);
this.state = {
value: this.props.value
};
}
getBadgeClasses() {
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;
}
handleIncrement = () => {
this.setState({value: this.state.value + 1});
}
render() {
return (
<div>
{this.props.children}
<span style={this.styles} className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button onClick={this.handleIncrement } className={"btn btn-secondary btn-sm"}>Increment</button>
<button
onClick={() => this.props.onDelete(this.props.id)} //The ID I'm trying to pass.
className={'btn btn-danger btn-sm m-2'}>
Delete
</button>
</div>
);
}
答案 1 :(得分:0)
我发现了问题,但没有映射ID。
更改了此
<Counter key={counter.id} onDelete={this.handleDelete} value={counter.value}>
对此
<Counter key={counter.id} onDelete={this.handleDelete} value={counter.value} id={counter.id}>