我正在尝试通过单击将子组件的已形成对象推送到 App.js 父组件。 据我了解,首先我应该在子组件中完成 newTask 对象,然后以某种方式将该对象推送到父组件中的 Tasks 对象。
https://codesandbox.io/s/test-login-page-tasks-rmfn5j?file=/src/components/NewTask.js:316-323
// Child component
const NewTask = ({ authors, tasks }) => {
const [title, setTitle] = useState("");
const [author, setAuthor] = useState("");
const [description, setDescription] = useState("");
const [status, setStatus] = useState(false);
const [priority, setPriority] = useState(false);
const sendTask = () => {
let newTask = {
title: title,
author: author,
description: description,
status: status,
priority: priority
};
};
<input onChange={(e) => setTitle(e.target.value)}/>
<input onChange={(e) => setDescription(e.target.value)}/>
<input onChange={(e) => setStatus(e.target.value)}/>
<input onChange={(e) => setPriority(e.target.value)}/>
<button onClick={sendTask}>Save</button>
}
// App parent component
const Tasks = [ //push newTask to this array
{
id: "001",
status: 0,
priority: 2,
title: "Develop website homepage",
description:
"Create a visually appealing and responsive homepage for the website",
schedule: {
creation_time: "2021-07-23T10:00:00"
},
author_name: "John Smith"
},
{
id: "002",
status: 1,
priority: 1,
title: "Implement user authentication",
description: "Add user authentication feature to the website",
schedule: {
creation_time: "2021-07-24T14:30:00"
},
author_name: "Sarah Lee"
}
]
function App() {
return (
<NewTask authors={Authors} tasks={Tasks} />
)}
App
为Tasks
组件创建一个状态。App.tsx
:
function App() {
const [tasks, setTasks] = useState(Tasks);
return (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route path="/" exact={true}>
<Login authors={Authors} />
</Route>
<Route path="/taskslist">
<Taskslist Tasks={tasks} />
</Route>
<Route path="/newtask">
<NewTask
authors={Authors}
onFinish={(newTask) => {
setTasks((pre) => [
...pre,
{ ...newTask, id: Math.random().toString() }
]);
}}
/>
</Route>
<Route path="/errorlogin">
<ErrorLogin />
</Route>
</Switch>
</div>
</BrowserRouter>
);
}
export default App;
onFinish
组件公开一个 NewTask
函数属性。您可以在创建任务后调用它。然后调用 setTasks()
setter 函数来更新任务状态。NewTask.tsx
:
const sendTask = () => {
let newTask = {
title: title,
author: author,
description: description,
status: +status,
priority: priority
};
onFinish(newTask);
history.replace("/taskslist");
};