[英]Pass true/false state from functional component in react
I would like to read this component's state in other components.我想在其他组件中读取此组件的状态。
I keep looking for tutorials but i cant find any that explain it in the way that i need.我一直在寻找教程,但我找不到任何以我需要的方式解释它的教程。
export default function Task({ task }) {
const [isDone, setIsDone] = React.useState(false);
return (
<TaskWrapper>
<CheckBox>
<NotDone isDone={isDone} onClick={() => setIsDone(true)} />
<Done
isDone={isDone}
src={checkMark}
alt={"is done"}
onClick={() => setIsDone(false)}
/>
</CheckBox>
<Todo>{task}</Todo>
</TaskWrapper>
);
}
How do i pass "isDone" to an other component and then check if it's true or false and then act on that information??我如何将“isDone”传递给其他组件,然后检查它是真还是假,然后根据该信息采取行动?
Thanks in advance!提前致谢!
EDIT:编辑:
I would like to know if a task is done or not in here.我想知道这里是否完成了任务。
export default function TodoList() {
return (
<Todos>
<Task task={"Task 1"} />
<Task task={"Task 2"} />
<Task task={"Task 3"} />
</Todos>
);
}
You could do this with context, but I believe there is more simple solution.你可以用上下文来做到这一点,但我相信有更简单的解决方案。 You just have to keep tasks information in TodoList.
你只需要在 TodoList 中保存任务信息。
const tasks = [{name: "task 1", id: 1}, {name: "task 2", id: 2}]
export default function TodoList() {
const [completedTasks, setCompletedTasks] = React.useState([]);
return (
<Todos>
{tasks.map((task) =>
<Task
task={task.name}
isDone={completedTasks.includes(task.id)}
onComplete={() => setCompletedTasks([...completedTasks, task.id)])}
onRemoveFromCompleted={() => setCompleted(...completedTasks.filter(t => t.id !== task.id)))} />)}
</Todos>
);
} }
And than in task component just pass the values like so而不是在任务组件中传递这样的值
export default function Task({ task, isDone, onComplete, onRemoveFromCompleted }) {
return (
<TaskWrapper>
<CheckBox>
<NotDone isDone={isDone} onClick={onComplete} />
<Done
isDone={isDone}
src={checkMark}
alt={"is done"}
onClick={onRemoveFromCompleted}
/>
</CheckBox>
<Todo>{task}</Todo>
</TaskWrapper>
);
}
Can't you just pass props from the Task component to the TodoList component?不能直接从 Task 组件传递 props 到 TodoList 组件吗?
export default function Task({ task }) {
const [isDone, setIsDone] = React.useState(false);
return (
<TaskWrapper
isDone={isDone}
>
<CheckBox>
<NotDone isDone={isDone} onClick={() => setIsDone(true)} />
<Done
src={checkMark}
alt={"is done"}
onClick={() => setIsDone(false)}
/>
</CheckBox>
<Todo>{task}</Todo>
</TaskWrapper>
);
}
export default function TodoList(props) {
return (
<Todos>
<Task isDone={props.isDone} />
</Todos>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.