Is it possible to pass a function with an id parameter from a child component to a parent component using React? I'm trying to pass the function as a prop to it's parent component. The component solution is App component-> TasksList component-> Task component. So I need to route to a specific task by clicking on it, and use its individual ID. The point is, when the url is clicked and routed to the task, it changes to /task/009, but the task component does not render.
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
Multiple questions
In your application components, you do not render task components for individual task routes. To solve this problem, you can define a route for a single task in the application component and render the task component for that route, like this: {task.description} Let me know if I need further assistance. function App() {
const [tasks, setTasks] = useState(Tasks);
return (
Task
component you need to ensure that the selected task is filtered from the URL. Use useParams()
import { useParams } from "react-router";
const Task = ({ Tasks }) => {
const { id } = useParams();
const task = Tasks.find((task) => task.id === id);
return (
{task.title}