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

React Native中如何清除已提交的文本输入框内容?

解决提交Firebase后清空输入框的问题

你的代码目前存在几个关键问题导致清空输入框失败:

  • 没有调用create函数(你写的create只是引用函数,没有执行)
  • 只清空了nombre的状态,另外两个输入框的状态没处理
  • 清空逻辑没有和数据提交成功的事件绑定,可能出现提交失败但输入框被清空的情况

修改方案:

  1. 在onPress里执行create()函数,确保点击时触发提交逻辑
  2. 在create函数的then回调中重置所有输入框的状态,保证只有数据成功提交后才清空输入框

修改后的完整代码:

import { useState } from 'react';
import { StyleSheet, Text, View, TextInput, TouchableOpacity } from 'react-native';
import { addDoc, collection } from "firebase/firestore";
import { db } from './components/config';

export default function App() {

  const [nombre, setNombre] = useState('');
  const [cantidad, setCantidad] = useState('');
  const [pretexto, setPretexto] = useState('');

  function create(){
    //Submit data
    addDoc(collection(db, "users"), {
      nombre: nombre,
      cantidad: cantidad,
      pretexto: pretexto
    }).then(() => {
      console.log('Data submitted');
      // 数据提交成功后清空所有输入框状态
      setNombre('');
      setCantidad('');
      setPretexto('');
    }).catch((error) => {
      console.log(error);
    })
  }

  return (
    <View style={styles.container}>
      <View style={styles.textBox}>
        <TextInput value={nombre} onChangeText={(nombre) => setNombre(nombre)} placeholder='Nombre del caretubo' style={styles.inputOne}></TextInput>
        <TextInput value={cantidad} onChangeText={(cantidad) => setCantidad(cantidad)} placeholder='Cantidad que debe el HP' style={styles.inputTwo}></TextInput>
        <TextInput value={pretexto} onChangeText={(pretexto) => setPretexto(pretexto)} placeholder='Pretexto' style={styles.inputThree}></TextInput>
        <TouchableOpacity style={styles.botonaso} onPress={create}>
          <Text style={styles.botonasoTexto}>Subir</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  textBox: {
    width: '100%',
    padding: 12,
    borderColor: 'gray',
    borderWidth: 1,
    borderRadius: 20,
  },
  inputOne: {
    fontSize: 15,
  },
  inputTwo: {
    fontSize: 15,
  },
  inputThree: {
    fontSize: 15
  },
  botonaso: {
    backgroundColor: '#202A44',
    alignItems: 'center',
    borderRadius: 20,
    padding: 10
  },
  botonasoTexto: {
    color: 'white'
  }
});

关键修改点说明:

  • onPress直接绑定create函数(也可以写onPress={() => create()},效果一致),确保点击时执行提交逻辑
  • 在addDoc的then回调中添加了三个状态的重置,保证数据成功写入后才清空输入框
  • 移除了代码中未使用的doc和setDoc导入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:54:18