Silver Library (Archived)
OOP, but how with reactjs? 본문
I already used number of features those provided by react.js, but I just noticed one thing.
Have I followed OOP by the way?
What about design pattern?
Above all, how can I apply such OOP norm to any of them?
So, let me clarify.
OOP approach with classes are:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { message: 'Hello, World!' };
}
handleClick() {
this.setState({ message: 'Hello, React!' });
}
render() {
return (
<div>
<p>{this.state.message}</p>
<button onClick={() => this.handleClick()}>
Click me
</button>
</div>
);
}
}
In this example, MyComponent is a class that extends React.Component.
There is a constructorfunction that calls the parent class's constructor and sets an initial state for the component.
The render method is used to return the JSX, which will be rendered to the screen.
The component also has a handleClick method that updates the component's state when the button is clicked.
Wait, what about the usual instance?
import { useState, useEffect } from 'react'
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`You clicked ${count} times`);
}, [count])
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In this case, MyComponent is functional component that uses useState hook to manage the componnet's state.
Then useEffect hook to perform a side effect, like updating the count when the button is clicked.
'F5. Library of Tools > React.js' 카테고리의 다른 글
미궁의 react hook form, 대체 어떻게 전달될까. (0) | 2023.02.25 |
---|---|
Crash note - list, key, fake data generator (0) | 2023.01.28 |
So, how to useEffect? (0) | 2023.01.11 |