Sure! Here’s an example of a class component in React:
import React, { Component } from 'react';
class MyClassComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
incrementCount = () => {
this.setState(prevState => ({ count: prevState.count + 1 }));
};
render() {
const { count } = this.state;
return (
<div>
<h1>My Class Component</h1>
<p>Count: {count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
export default MyClassComponent;
In this example, MyClassComponent
extends the Component
class provided by React. It has an initial state count
set to 0. The incrementCount
method is used to update the count
state when the button is clicked. The component renders a heading, the current count, and a button to increment the count.