首页 > 解决方案 > 在 fetch 开始 React Native 后制作不可点击的按钮

问题描述

我试图在获取开始后禁用我的按钮,这样他们就不能进行多次获取,当获取完成以使其进程使按钮再次可点击时,你知道如何实现吗?

这是我的代码:

import React from 'react';
import { StyleSheet, Text, View, Button, ActivityIndicator } from 'react-native';


export default function App() {

  const [nombre,setNombre]= React.useState('');
  const [isLoading,setIsLoading]= React.useState(false);
  

  const fetchDatos = async () => {
    setIsLoading(true);
    return fetch('http://localhost:8000/api/consulta', {method: 'POST', headers: new Headers({'Accept': 'application/json',
         'Content-Type': 'application/json',

       }),       body: JSON.stringify({
         codigoParticipante: '1520',
         contrato: '135927',
      })}).then(response => {
      return response.json();
})
  .then(responseJson => {

  
      setIsLoading(false);
      setNombre(responseJson.Participante.InfoParticipante['@attributes'].Nombre);
  }}).catch(function() {
    alert("Sorry, server offline");
  });
} 
  
  return (
    <View>
    <Button 
      title='press me'
      onPress={fetchDatos}
    />
    <Text>{nombre}</Text>
    {isLoading && (
        <ActivityIndicator
            style={[{height: 80}]}
            color="#C00"
            size="large"
            hidesWhenStopped={true}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

任何建议我都会非常感激!

标签: javascriptreactjsreact-native

解决方案


获取时禁用按钮

 <Button 
  title='press me'
  onPress={fetchDatos}
  disabled = {isLoading}
/>

推荐阅读