Сделали выключатель для лампочки

This commit is contained in:
2026-06-11 20:43:08 +03:00
parent de33066cbe
commit 55c4ae7d53
3 changed files with 57 additions and 43 deletions
+22 -39
View File
@@ -1,49 +1,32 @@
import React, { useState, useEffect } from 'react'
import { produce } from 'immer'
import { create } from 'zustand'
const useLightStore = create(set => ({
isLightOn: false,
toggleLight: () => set(state => ({isLightOn: !state.isLightOn})),
turnOn: () => set({isLightOn:true}),
turnOff: () => set({isLightOn:false}),
}))
function LightButton() {
const toggleLight = useLightStore(state => state.toggleLight)
return (<button onClick={toggleLight}>Переключить свет</button>)
}
function LightOff() {
const lightOff = useLightStore(state => state.turnOff)
return (<button onClick={lightOff}>Выключить свет</button>)
}
function App() {
const [tasks,setTasks] = useState([])
const [input,setInput] = useState('')
const isLightOn = useLightStore(state => state.isLightOn)
const addTask = () => {
if(!input.trim()) return
setTasks(currentTasks => produce(currentTasks, draft => {
draft.push({
id: Date.now(),
text: input.trim(),
done: false
})
}))
setInput('')
}
const toggleTask = id => {
setTasks(currentTask => produce(currentTask, draft => {
const task = draft.find(t => t.id === id)
if(task) {
task.done = !task.done
}
}))
}
const removeTask = id => {
setTasks(currentTask => produce(currentTask, draft => {
const index = draft.findIndex(t => t.id === id)
if (index !== -1)
draft.splice(index,1)
}))
}
return (
<>
<h1>Практика по созданию списка задач</h1>
<input value={input} onChange={e=>setInput(e.target.value)} />
<button onClick={addTask}>Добавить</button>
<ul>{tasks.map(({id,text,done}) => (
<li key={id} style={{ textDecoration: done ? 'line-through' : 'none'}}>
<input type="checkbox" checked={done} onChange={()=> toggleTask(id)} />
{text}
<button onClick={() => removeTask(id)}>Удалить</button>
</li>
))}</ul>
<div>Лампочка: {isLightOn ? 'Включена' : 'Выключена'}</div>
<LightButton />
<LightOff />
</>
)
}