Compare commits

..

2 Commits

Author SHA1 Message Date
laktionov-as 12515f925d Сделали таймер 2026-05-28 20:45:57 +03:00
laktionov-as b3662b759f class components 2026-05-28 20:29:26 +03:00
+86 -76
View File
@@ -1,98 +1,108 @@
import { useState, useRef, useEffect } from 'react' import React from 'react'
function Example() { class MyComponent extends React.Component {
const myRef = useRef(null); constructor(props) {
const counterRef = useRef(0); super(props);
const [text, setText] = useState(''); this.state = { data: null };
this.handleClick = this.handleClick.bind(this);
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() { render() {
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 ( return (
<div> <div>
Текущее значение: {value} <br /> {this.state.data ? (
Предыдущее значение: {prevValueRef.current} <div>Данные: {this.state.data}</div>
) : (
<div>Загрузка...</div>
)}
<button onClick={this.handleClick}>Обновить</button>
</div> </div>
) )
} }
function ScrollList() { componentDidMount() {
const listRef = useRef(null); fetch('https://api.example.com/data')
.then(responce => responce.json())
.then(json => this.setState({data: json}));
const scrollToBottom = () => { this.timerId = setInterval(()=> console.log('Tick'), 1000);
if(listRef.current) { }
listRef.current.scrollTop = listRef.current.scrollHeight;
componentWillUnmout() {
clearInterval(this.timerId);
}
handleClick() {
this.setState({data: 'Данные'})
} }
} }
return ( class MyComponent2 extends React.Component {
<> controller = new AbortController()
<div ref={listRef}
style={{height: 200, overflowY: 'auto', border: '1px solid black'}}> componentDidMount() {
{[...Array(20)].map((_,i)=>( fetch('https://api.example.com/data',{ singnal: this.controller.signal })
<div key={i}>Элемент {i + 1}</div> .then(responce => responce.json())
))} .then(json => this.setState({data: json}))
</div> .catch(error => {
<button onClick={scrollToBottom}>Прокрутить вниз</button> if(error.name == 'AbortError') {
</> console.log('Aborted');
) } else {
console.log('Other error',error);
}
});
}
componentWillUnmount() {
this.controller.abort()
}
}
class MyComponent3 extends React.Component {
componentDidMount() {
this.loadData();
}
async loadData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
this.setSate({ data });
} catch {
console.log('error');
}
}
}
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 }
}
componentDidMount() {
console.log('Timer mounted');
this.interval = setInterval(()=>{
this.setState(prevState => ({seconds: prevState.seconds + 1}))
},1000);
}
componentWillUnmount() {
console.log('Timer unmount');
clearInterval(this.interval);
}
render() {
return <h2>Прошло секунд: {this.state.seconds}</h2>
}
} }
function App() { function App() {
const [show,setShow] = React.useState(true);
return ( return (
<> <>
<h1>Hello, React!</h1> <h1>Таймер с классом</h1>
<ScrollList /> <button onClick={()=>setShow(prev => !prev)}>{show ? 'Скрыть' : 'Показать'} таймер</button>
{show && <Timer />}
</> </>
) )
} }