是否可以使用 React 将带有 id 参数的函数从子组件传递到父组件? 我试图将该函数作为道具传递给它的父组件。 组件的方案是App组件-> TasksList组件-> Task组件。因此,我需要通过单击特定任务来路由到该任务,并使用其单独的 ID。 重点是,点击 url 后路由到任务后,会更改为 /task/009,但任务组件不会呈现。
https://codesandbox.io/s/test-login-page-tasks-rmfn5j?file=/src/components/Taskslist.js
//App component const Tasks = [ { 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() { const [tasks, setTasks] = useState(Tasks); return ( <Route path="/taskslist"> <Taskslist Tasks={tasks} /> </Route> ) // Parent component import React from "react"; const Taskslist = ({ Tasks }) => { const history = useHistory(); const goToTask = (taskId) => { history.push(`/task/${taskId}`); }; return ( <Task Tasks={Tasks.filter((task) => task.status === 0)} goToTask={goToTask} /> } //Child component import React from "react"; const Task = ({ Tasks, goToTask }) => { return ( <div className="wrapper"> {Tasks.map((task) => ( <div key={task.id} onClick={goToTask(task.id)}> <h3>{task.title}</h3> </div> ))} </div> ); }; export default Task;
P粉5628459412024-03-21 00:29:19
多个问题
在您的应用程序组件中,您不会为各个任务路由渲染任务组件。要解决此问题,您可以在应用程序组件中为单个任务定义一个路由,并为该路由渲染任务组件,如下所示: {task.description} 让我知道是否需要进一步的帮助。function App() {
const [tasks, setTasks] = useState(Tasks);
return (
Task
组件中,您需要确保从 URL 中过滤所选任务。使用 useParams()
import { useParams } from "react-router";
const Task = ({ Tasks }) => {
const { id } = useParams();
const task = Tasks.find((task) => task.id === id);
return (
{task.title}