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

React Native中如何将AddTask组件的输入数据传递到App.js

React Native组件间传值实现待办添加

核心思路

子组件(AddTask)通过调用父组件(App.js)传递的回调函数,把输入的任务数据传回父组件。


1. 修改App.js

  • 新增处理添加任务的函数,接收子组件传来的任务文本,更新状态并打印
  • 将该函数作为props传给AddTask组件
  • 遍历todos数组渲染Task组件,替代原来的硬编码

修改后的代码:

import { StatusBar } from 'expo-status-bar';
import React, { useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Task from './components/Task';
import AddTask from './components/AddTask';

export default function App() {
  const [todos, setTodos] = useState([
    { text: 'hello', key: '1' },
  ]);

  // 接收子组件传来的任务,更新状态并打印
  const handleAddTodo = (taskText) => {
    if (taskText.trim()) {
      const newTodo = {
        text: taskText,
        key: Date.now().toString() // 用时间戳生成唯一key
      };
      setTodos([...todos, newTodo]);
      console.log('新增任务:', taskText);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.taskWrapper}>
        <Text style={styles.header}>Today's Tasks</Text>
      </View>

      <View style={styles.tasks}>
        {/* 遍历todos渲染Task组件 */}
        {todos.map(todo => (
          <Task key={todo.key} text={todo.text} />
        ))}
      </View>

      <View style={styles.addTask}>
        {/* 把回调函数传给AddTask */}
        <AddTask onAddTask={handleAddTodo} />
      </View>

      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#E8EAED',
  },
  taskWrapper: {
    paddingTop: 80,
    paddingHorizontal: 20,
  },
  header: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  tasks: {
    flex: 1,
  },
  addTask: {
    paddingBottom: 20,
  },
});

2. 修改AddTask.js

  • 删除自身的taskItems状态,任务列表状态由父组件统一管理
  • 点击加号按钮时,调用父组件传来的onAddTask函数,传入输入的任务文本
  • 清空输入框

修改后的代码:

import React, { useState } from 'react';
import { View, Text, Keyboard, StyleSheet, TextInput, TouchableOpacity, TouchableWithoutFeedback, Platform } from 'react-native';
import KeyboardAvoidingView from 'react-native/Libraries/Components/Keyboard/KeyboardAvoidingView';
import Task from './Task';

const AddTask = ({ onAddTask }) => { // 接收父组件的回调函数
  const [task, setTask] = useState('');

  const handleAddTask = () => {
    if (task.trim()) {
      onAddTask(task); // 调用父组件的函数,传递任务文本
      setTask(''); // 清空输入框
    }
  };

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={styles.container}>
      <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
        <View style={styles.container}>
          <View style={styles.inputContainer}>
            <TextInput 
              style={styles.input} 
              value={task} 
              onChangeText={text => setTask(text)} 
              placeholder={'Write a task'} 
            />
          </View>
          {/* 点击按钮调用handleAddTask */}
          <TouchableOpacity onPress={handleAddTask}>
            <View style={styles.plusButton}>
              <Text style={styles.plus}>+</Text>
            </View>
          </TouchableOpacity>
        </View>
      </TouchableWithoutFeedback>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingBottom: 20,
  },
  inputContainer: {
    flex: 1,
    marginRight: 10,
  },
  input: {
    height: 60,
    borderWidth: 1,
    padding: 10,
    borderRadius: 60,
    backgroundColor: '#fff',
    borderColor: 'white',
  },
  plusButton: {
    width: 60,
    height: 60,
    borderWidth: 1,
    borderRadius: 15,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    borderColor: 'white',
  },
  plus: {
    fontWeight: 'bold',
    fontSize: 24,
    color: '#E8EAED',
  },
  Task:{
    backgroundColor: '#fff',
    padding: 20,
    marginTop:10,
    marginHorizontal:20,
    borderRadius:10,
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'space-between',
    marginBottom:20,
  },
});

export default AddTask;

关键改动说明

  • 父组件通过props传递回调函数,子组件调用该函数传递数据,这是React父子组件传值的标准方式
  • 任务列表状态统一放在父组件管理,符合单一数据源原则
  • 增加空值判断,避免添加无效的空任务
  • 用时间戳生成唯一key,解决列表渲染的key冲突问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:18:31