Compare commits

..

2 Commits

3 changed files with 31 additions and 80 deletions
+27 -61
View File
@@ -1,78 +1,44 @@
import { useState, createContext, useContext } from 'react' import React from 'react'
import styles from './App.module.scss'
const UserContext = createContext('') class Clock extends React.Component {
constructor(props) {
function UserProvider({ children }) { super(props)
const [name,setName] = useState(''); this.state = { time: new Date().toLocaleTimeString() }
const toggleName = (newName) => {
setName(newName);
} }
return ( componentDidMount() {
<UserContext.Provider value={{name, toggleName}}> this.timerId = setInterval(()=>{
{children} this.setState({ time: new Date().toLocaleTimeString() })
</UserContext.Provider> }, 1000);
) console.log('Таймер смонтирован')
}
function Form() {
const {name, toggleName} = useContext(UserContext)
const [newName,setNewName] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
toggleName(event.target[0].value)
} }
const handlerChange = (event) => {
setNewName(event.target.value); componentDidUpdate(prevProps,prevState) {
console.log('Компонент обнвлен')
} }
return (
<form onSubmit={handleSubmit}>
<input type='text' value={newName} onChange={handlerChange} />
<button type='submit'>Войти</button>
</form>
)
}
function ExitButton() { componentWillUnmount() {
const {name, toggleName} = useContext(UserContext) clearInterval(this.timerId)
console.log('Компонент таймера размонтирован')
return ( }
<button onClick={() => toggleName('')}>Выход</button>
)
}
function Toolbar() {
const {name, toggleName} = useContext(UserContext)
return(
<div className={styles.container}>
<h3>Панель пользователя</h3>
{name && `Привет ${name}`}
{name ? <ExitButton /> : <Form /> }
render() {
return <div>
<h2>Текущее время: {this.state.time}</h2>
</div> </div>
) }
}
function Page() {
return (
<div>
<h1 style={{textAlign: 'center'}}>Главная страница</h1>
<Toolbar />
</div>
)
} }
function App() { function App() {
const [showClock, setShowClock] = React.useState(true);
return ( return (
<> <>
{/* Добавьте тестовый контент для проверки */} <h1>Жизненный цикл компонента часов</h1>
<h1>Hello, React!</h1> <button onClick={()=> setShowClock(!showClock)}>
<UserProvider> {showClock ? 'Скрыть часы' : 'Показать часы' }
<Page /> </button>
</UserProvider> {showClock && <Clock />}
</> </>
) )
} }
-13
View File
@@ -1,13 +0,0 @@
.container {
height: 500px;
border: 1px solid black;
border-radius: 10px;
background-color: lightblue;
}
.item {
font-size: 16pt;
border: 1px dotted gray;
/*margin: 5px 10px;
padding: 10px;*/
border-radius: 5px;
}
-2
View File
@@ -4,7 +4,5 @@ import { createRoot } from 'react-dom/client'
import App from './App.jsx' import App from './App.jsx'
createRoot(document.getElementById('root')).render( createRoot(document.getElementById('root')).render(
<StrictMode>
<App /> <App />
</StrictMode>
) )