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