【问题标题】:Reset fields in a form after submitting data with React Native使用 React Native 提交数据后重置表单中的字段
【发布时间】:2021-02-03 23:18:12
【问题描述】:

我正在尝试使用表单将用户添加到我的数据库中,但是在单击提交按钮后,我也想重置表单中的字段。

我正在设置这样的状态,并尝试在 onPress 道具上提交我的数据:

export default function Cadastro({}) {
  const [nome, setNome] = useState("");
  const [idade, setIdade] = useState("");
  const [email, setEmail] = useState("");
  const [estado, setEstado] = useState("");
  const [cidade, setCidade] = useState("");
  const [endereco, setEndereco] = useState("");
  const [telefone, setTelefone] = useState("");
  const [nome_usuario, setNome_usuario] = useState("");
  const [senha, setSenha] = useState("");
  const [confirmacao, setConfirmacao] = useState("");

  var newUser = {
    nome: nome,
    idade: idade,
    email: email,
    estado: estado,
    cidade_id: cidade,
    endereco: endereco,
    telefone: telefone,
    nome_usuario: nome_usuario,
    senha: senha,
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <FocusAwareStatusBar barStyle="light-content" backgroundColor="#88c9bf" />
      <ScrollView>
        <KeyboardAvoidingView style={styles.background}>
          <View style={styles.infobox}>
            <Text style={styles.infotext}>
              As informações preenchidas serão divulgadas apenas para a pessoa
              com a qual você realizar o processo de adoção e/ou apadrinhamento,
              após a formalização do processo.
            </Text>
          </View>

          <View style={styles.regform}>
            <Text style={styles.label}>INFORMAÇÕES PESSOAIS</Text>

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Nome completo"
              autoCorrect={false}
              value={nome}
              onChangeText={setNome}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Idade"
              autoCorrect={false}
              value={idade}
              onChangeText={setIdade}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="E-mail"
              autoCorrect={false}
              value={email}
              onChangeText={setEmail}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Estado"
              autoCorrect={false}
              value={estado}
              onChangeText={setEstado}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Cidade"
              autoCorrect={false}
              value={cidade}
              onChangeText={setCidade}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Endereço"
              autoCorrect={false}
              value={endereco}
              onChangeText={setEndereco}
            />

            <TextInput
              style={styles.textInput}
              placeholder="Telefone"
              autoCorrect={false}
              value={telefone}
              onChangeText={setTelefone}
            />

            <Text style={styles.label}>INFORMAÇÕES DE PERFIL</Text>

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Nome de usuário"
              autoCorrect={false}
              value={nome_usuario}
              onChangeText={setNome_usuario}
            />

            <TextInput
              style={[styles.textInput, { marginBottom: 36 }]}
              placeholder="Senha"
              autoCorrect={false}
              value={senha}
              onChangeText={setSenha}
            />

            <TextInput
              style={styles.textInput}
              placeholder="Confirmação de senha"
              autoCorrect={false}
              value={confirmacao}
              onChangeText={setConfirmacao}
            />

            <Text style={styles.label}>FOTO DE PERFIL</Text>

            <View style={styles.container}>
              <TouchableHighlight onPress={() => {}}>
                <View style={styles.button}>
                  <Image source={require("../../assets/controlpoint.png")} />
                  <Text style={{ color: "#757575" }}>adicionar fotos</Text>
                </View>
              </TouchableHighlight>
            </View>

            <View style={{ paddingTop: 32, paddingBottom: 24 }}>
              <SubmitButton
                text="FAZER CADASTRO"
                onPress={() => {
                  AddUsuario(newUser);
                }}
              />
            </View>
          </View>
        </KeyboardAvoidingView>
      </ScrollView>
    </SafeAreaView>
  );
}

我还尝试创建一个设置状态的函数,例如setNome(''),但随后出现“无效的挂钩调用”错误。

另外,除了我上面的方法之外,还有没有更好的方法来初始化多个状态?

感谢您的帮助!

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    因为您使用的是函数式组件,所以您可以按如下方式使用 Hooks。如果你有条件渲染你的代码检查 todoInput 是否在传递给 useEffect 的函数中定义。我假设你的状态变量在依赖列表中被称为 todoText。

    import {useRef, useEffect} from 'react';
    
    
    let AddTodo = ({ dispatch }) => {
        const todoInput = useRef();
        useEffect(()=>todoInput.current.clear(),[todoText]);
    
          return (
              <TextInput 
                  ref={todoInput}
                  onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } } 
              />
          )
        }

    【讨论】:

      【解决方案2】:

      为所有字段更改此项

      "onChangeText={setNome}" 到 onChangeText={(text) => setNome(text)}

      提交后清除值

      const clearForm = () => {
          setName('');
          setIdade('');
          ......
      }
      
      <SubmitButton
         text="FAZER CADASTRO"
         onPress={() => {
          AddUsuario(newUser);
          clearForm();
         }}
      />
      

      【讨论】:

      • 我正在尝试这种方式,但我收到了“无效的 Hook 调用”错误。
      • 我的 AddUsuario 函数正在导入并使用useEffect(),有问题吗?
      • 仅从 React 函数调用 Hooks。有一些 Hooks 规则可以使用,你可以检查一下并相应地实施stackoverflow.com/questions/56663785/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2021-09-12
      • 2021-07-02
      • 2016-03-31
      • 2019-05-26
      相关资源
      最近更新 更多