I was following Mosh Hamedani 's tutorial here for creating react-app .
I did exactly what he said.
I'm trying to pass an argument called product
to a function which is called for onClick
However, I'm getting an error for which I didn't find much info.
Here's the code:
import React, { Component } from "react";
class Counter extends Component {
state = {
count: 0
};
formatCount() {
return this.state.count === 0 ? "Zero" : this.state.count;
}
handleIncrement = product => {
console.log(product);
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<React.Fragment>
<span className={this.formatSpan()}>{this.formatCount()}</span>
<button
onClick={() => this.handleIncrement(product)}
className="btn btn-primary"
>
Increment
</button>
</React.Fragment>
);
}
}
export default Counter;
Here's the error:
Failed to compile.
./src/components/counter.jsx Line 41: 'product' is not defined no-undef
Search for the keywords to learn more about each error.
you are passing product as variable which is not defined pass parameter with inverted comas other wise declare it and assing a value.
use
onClick={() => this.handleIncrement("product")}
product was never defined in your component. therefor it is not defined. you can declare product in your component state, or pass a product to the component as a prop.
下面的代码对我有用:
onClick={(product) => this.handleIncrement(product)}
Following that same tutorial, I had the same problem. What I understand is that the "product" here is refering to the event. Like H_R_S suggested, using this code:
handleIncrement = (product) => {
console.log(product);
this.setState({count : this.state.count + 1});
}
render() {
return (
<React.Fragment>
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button onClick={(product) => this.handleIncrement(product)} className="btn btn-secondary btn-sm">Increment</button>
</React.Fragment>
);
}
you will be able to see the event in the console :
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.