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

在React Native中如何点击Button触发onPress生成新组件

点击按钮动态生成新增条目的实现方案

核心实现逻辑

所有前端框架的实现底层逻辑统一:

  • 声明一个响应式数组存储所有条目的对应数据,每个数组元素对应一个条目组件的渲染参数
  • onPress触发时往数组末尾追加一条符合数据结构的默认/空数据
  • 视图层通过列表渲染语法遍历数组,批量生成条目组件
  • 后续需要修改、删除条目时,直接操作该数组的对应元素即可,视图会自动同步更新

React/React Native 实现示例

import { useState } from 'react';
import { View, Text, Button } from 'react-native';

// 封装独立的待办条目组件
const TodoItem = ({ content }) => {
  return (
    <View style={{ padding: 10, borderBottomWidth: 1, borderBottomColor: '#eee' }}>
      <Text>{content}</Text>
    </View>
  )
}

export default function TodoApp() {
  // 响应式数组存储所有待办数据
  const [todoList, setTodoList] = useState([
    { id: 1, content: '默认待办任务1' }
  ])

  // 按钮点击触发的新增逻辑
  const handleAddItem = () => {
    const newItem = {
      // 时间戳作为唯一id,业务场景可替换为后端返回的业务id
      id: Date.now(),
      content: `新增待办任务${todoList.length + 1}`
    }
    setTodoList([...todoList, newItem])
  }

  return (
    <View style={{ flex: 1, padding: 20 }}>
      {/* 遍历数组渲染所有条目 */}
      {todoList.map(item => (
        <TodoItem key={item.id} content={item.content} />
      ))}
      <Button title="新增待办" onPress={handleAddItem} />
    </View>
  )
}

Vue 实现示例

<template>
  <div style="padding: 20px;">
    <TodoItem v-for="item in todoList" :key="item.id" :content="item.content" />
    <button @press="handleAddItem">新增待办</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import TodoItem from './TodoItem.vue'

// 响应式数组存储所有待办数据
const todoList = ref([
  { id: 1, content: '默认待办任务1' }
])

// 按钮点击触发的新增逻辑
const handleAddItem = () => {
  const newItem = {
    id: Date.now(),
    content: `新增待办任务${todoList.value.length + 1}`
  }
  todoList.value.push(newItem)
}
</script>

注意事项

  • 列表渲染必须给每个条目添加唯一key属性,禁止使用数组下标作为key,否则条目增删时会出现视图渲染错乱
  • 需要支持条目编辑、删除功能时,直接修改数组对应下标的元素即可,框架会自动同步视图
  • 如果是Web端React场景,将示例中的React Native原生组件替换为div、原生button即可,逻辑完全通用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:54:02