Compare commits

..

1 Commits

Author SHA1 Message Date
laktionov-as 7607146ff1 Разобрали useRef 2026-05-21 20:34:06 +03:00
+85 -31
View File
@@ -1,44 +1,98 @@
import React from 'react' import { useState, useRef, useEffect } from 'react'
class Clock extends React.Component { function Example() {
constructor(props) { const myRef = useRef(null);
super(props) const counterRef = useRef(0);
this.state = { time: new Date().toLocaleTimeString() } const [text, setText] = useState('');
useEffect(() => {
myRef.current?.focus();
},[]);
const handlerFocus = () => {
if(myRef.current) {
myRef.current.focus();
}
};
const handlerChange = (event) => {
setText(event.target.value);
}
counterRef.current += 1;
return <div>
<input ref={myRef} text="text" /><br />
Количество рендров: {counterRef.current}<br />
<input text="text" onChange={handlerChange} value={text} />
<button onClick={handlerFocus}>Поставить фокус на поле</button>
</div>
}
function ClickCounter() {
const countRef = useRef(0);
function handlerClick() {
countRef.current += 1;
//alert(`Нажали ${countRef.current} раз.`);
}
return <button onClick={handlerClick}>Нажать</button>;
}
function TimerComponent() {
const timerIdRef = useRef(null);
useEffect(() => {
timerIdRef.current = setTimeout(() => {
alert("Прошло 3 секунды");
}, 3000);
return () => {
clearTimeout(timerIdRef.current);
}
},[]);
}
function PrevValue({ value }) {
const prevValueRef = useRef();
useEffect(() => {
prevValueRef.current = value;
});
return (
<div>
Текущее значение: {value} <br />
Предыдущее значение: {prevValueRef.current}
</div>
)
}
function ScrollList() {
const listRef = useRef(null);
const scrollToBottom = () => {
if(listRef.current) {
listRef.current.scrollTop = listRef.current.scrollHeight;
}
} }
componentDidMount() { return (
this.timerId = setInterval(()=>{ <>
this.setState({ time: new Date().toLocaleTimeString() }) <div ref={listRef}
}, 1000); style={{height: 200, overflowY: 'auto', border: '1px solid black'}}>
console.log('Таймер смонтирован') {[...Array(20)].map((_,i)=>(
} <div key={i}>Элемент {i + 1}</div>
))}
componentDidUpdate(prevProps,prevState) {
console.log('Компонент обнвлен')
}
componentWillUnmount() {
clearInterval(this.timerId)
console.log('Компонент таймера размонтирован')
}
render() {
return <div>
<h2>Текущее время: {this.state.time}</h2>
</div> </div>
} <button onClick={scrollToBottom}>Прокрутить вниз</button>
</>
)
} }
function App() { function App() {
const [showClock, setShowClock] = React.useState(true);
return ( return (
<> <>
<h1>Жизненный цикл компонента часов</h1> <h1>Hello, React!</h1>
<button onClick={()=> setShowClock(!showClock)}> <ScrollList />
{showClock ? 'Скрыть часы' : 'Показать часы' }
</button>
{showClock && <Clock />}
</> </>
) )
} }