You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何点击子组件按钮将构建好的对象传递给App.js父组件

解决方案:React子组件向父组件传递对象并更新数组

要实现子组件构建对象后传递给父组件并添加到数组,核心是通过props传递回调函数完成父子组件通信,同时父组件需维护可更新的状态。以下是具体修改步骤:

1. 父组件(App.js)修改

  • 将原常量Tasks改为useState状态,确保数组可更新
  • 定义回调函数接收子组件传来的新任务,用于更新任务列表
  • 将回调函数作为props传递给子组件

修改后的App组件代码:

import { useState } from 'react';
import NewTask from './components/NewTask';

// 初始任务数据
const initialTasks = [
{
  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() {
  // 用useState维护任务列表状态
  const [tasks, setTasks] = useState(initialTasks);

  // 定义添加任务的回调函数
  const addNewTask = (newTask) => {
    // 生成唯一id,这里用时间戳简单实现,可按需调整
    const taskWithId = {
      ...newTask,
      id: Date.now().toString(),
      schedule: {
        creation_time: new Date().toISOString()
      }
    };
    // 更新任务数组,遵循React状态不可变性原则
    setTasks(prevTasks => [...prevTasks, taskWithId]);
  };

  return (
    <NewTask authors={Authors} addNewTask={addNewTask} />
  );
}

export default App;

2. 子组件(NewTask.js)修改

  • 接收父组件传递的addNewTask回调函数
  • 在sendTask中调用该回调,传递构建好的任务对象
  • 调整状态类型,匹配父组件的字段格式,比如status和priority改为数字类型

修改后的NewTask组件代码:

import { useState } from 'react';

const NewTask = ({ authors, addNewTask }) => {
  const [title, setTitle] = useState("");
  const [authorName, setAuthorName] = useState("");
  const [description, setDescription] = useState("");
  const [status, setStatus] = useState(0); // 与父组件保持数字类型
  const [priority, setPriority] = useState(1); // 与父组件保持数字类型

  const sendTask = () => {
    // 构建符合父组件格式的任务对象
    let newTask = {
      title: title,
      author_name: authorName, // 字段名与父组件统一
      description: description,
      status: parseInt(status),
      priority: parseInt(priority)
    };
    // 调用父组件回调,传递新任务
    addNewTask(newTask);
    // 可选:清空表单输入
    setTitle("");
    setAuthorName("");
    setDescription("");
    setStatus(0);
    setPriority(1);
  };

  return (
    <div>
      <input 
        type="text" 
        value={title} 
        onChange={(e) => setTitle(e.target.value)} 
        placeholder="任务标题"
      />
      <input 
        type="text" 
        value={authorName} 
        onChange={(e) => setAuthorName(e.target.value)} 
        placeholder="作者"
      />
      <input 
        type="text" 
        value={description} 
        onChange={(e) => setDescription(e.target.value)} 
        placeholder="任务描述"
      />
      <input 
        type="number" 
        value={status} 
        onChange={(e) => setStatus(e.target.value)} 
        min="0" max="2"
        placeholder="状态(0/1/2)"
      />
      <input 
        type="number" 
        value={priority} 
        onChange={(e) => setPriority(e.target.value)} 
        min="1" max="3"
        placeholder="优先级(1/2/3)"
      />
      <button onClick={sendTask}>Save</button>
    </div>
  );
};

export default NewTask;

关键说明

  • React中状态只能由拥有它的组件修改,子组件不能直接修改父组件数组,必须通过回调通知父组件更新
  • 保持任务对象字段格式与父组件一致,避免数据不匹配
  • 更新数组时使用展开运算符创建新数组,确保状态更新的不可变性

内容的提问来源于stack exchange,提问作者user20984971

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 22:45:32