Сделали компонент часов

This commit is contained in:
2026-06-02 19:51:47 +03:00
parent c137c644e3
commit 5ee1bf2eee
+16 -11
View File
@@ -1,39 +1,44 @@
import React from 'react'
class MyComponent extends React.Component {
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0 }
this.state = { time: new Date().toLocaleTimeString() }
}
componentDidMount() {
console.log('Компонент смонтирован')
this.timerId = setInterval(()=>{
this.setState({ time: new Date().toLocaleTimeString() })
}, 1000);
console.log('Таймер смонтирован')
}
componentDidUpdate(prevProps,prevState) {
console.log('Компонент обнвлен')
if(prevState.count !== this.state.count) {
console.log('Состояние изменилось')
}
}
componentWillUnmount() {
console.log('Компонент будет размонтирован')
clearInterval(this.timerId)
console.log('Компонент таймера размонтирован')
}
render() {
return <div>
Привет мир! {this.props.name} {this.state.count}
<button onClick={()=> this.setState({ count: this.state.count })}>Жми!</button>
<h2>Текущее время: {this.state.time}</h2>
</div>
}
}
function App() {
const [showClock, setShowClock] = React.useState(true);
return (
<>
<h1>Hello, React!</h1>
<MyComponent name="Alex" />
<h1>Жизненный цикл компонента часов</h1>
<button onClick={()=> setShowClock(!showClock)}>
{showClock ? 'Скрыть часы' : 'Показать часы' }
</button>
{showClock && <Clock />}
</>
)
}