How to use function in react class components ?
2023-10-12
I know how you felt when you first saw this title, trust me, i know what were you thinking?
Are you joking? Use function?
That's too easy, right? const addition= () => And then use it, just make it?
But, but, for beginners, I believe there will be some problems that you will meet
Now,there is a requirement. Every time the number is clicked, the number will increase by 1.
import React, { PureComponent } from "react";
export default class Demo extends PureComponent {
constructor(props) {
super(props);
this.state = {
num: 0,
};
}
addNum() {
const { num } = this.state;
this.setState({
num: num + 1,
});
}
render() {
return (
// Use addNum method directly
<div onClick={this.addNum}>
<div>add</div>
<div>{this.state.num}</div>
</div>
);
}
}
import React, { PureComponent } from "react";
export default class Demo extends PureComponent {
constructor(props) {
super(props);
this.state = {
num: 0,
};
}
addNum() {
const { num } = this.state;
this.setState({
num: num + 1,
});
}
render() {
return (
// Use addNum method directly
<div onClick={this.addNum()}>
<div>add</div>
<div>{this.state.num}</div>
</div>
);
}
}
import React, { PureComponent } from "react";
export default class Demo extends PureComponent {
constructor(props) {
super(props);
this.state = {
num: 0,
};
}
addNum() {
const { num } = this.state;
this.setState({
num: num + 1,
});
}
render() {
return (
<div
onClick={() => {
this.addNum();
}}
>
<div>add</div>
<div>{this.state.num}</div>
</div>
);
}
}
import React, { PureComponent } from "react";
export default class Demo extends PureComponent {
constructor(props) {
super(props);
this.state = {
num: 0,
};
}
addNum = () => {
const { num } = this.state;
this.setState({
num: num + 1,
});
};
render() {
return (
<div onClick={this.addNum}>
<div>add</div>
<div>{this.state.num}</div>
</div>
);
}
}
import React, { PureComponent } from "react";
export default class Demo extends PureComponent {
constructor(props) {
super(props);
this.state = {
num: 0,
};
this.addNum = this.addNum.bind(this);
}
addNum() {
const { num } = this.state;
this.setState({
num: num + 1,
});
}
render() {
return (
<div onClick={this.addNum}>
<div>add</div>
<div>{this.state.num}</div>
</div>
);
}
}
Or you can upgrade react version to 16.8, then use hooks 😂 Because we need to consider this pointer problem in class component, i hate this,that is a devil!!!!!
Then you never need to consider this when you use hooks function component ❤