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

React Native 函数式组件中如何实现按钮点击一次后自动禁用?

实现方案

你可以通过React的useState钩子维护按钮的禁用状态,点击触发逻辑前先将状态置为禁用即可,修改后的代码如下:

import { useState } from 'react';
import { Button, Alert } from 'react-native';
// 其余原有导入保持不变

const YourComponent = () => {
  // 声明按钮禁用状态,初始为可点击
  const [isVerifyBtnDisabled, setIsVerifyBtnDisabled] = useState(false);

  const Verify = () => {
    // 点击后立刻禁用按钮,避免重复触发请求
    setIsVerifyBtnDisabled(true);
    firebase
      .auth()
      .currentUser.sendEmailVerification()
      .then(() => {
        Alert.alert('验证码已发送');
      })
      .catch(err => {
        // 如果业务需要请求失败后恢复按钮可点击,可取消下方注释
        // setIsVerifyBtnDisabled(false);
        Alert.alert('发送失败', err.message);
      });
  };

  return (
    <Button 
      onPress={Verify} 
      disabled={isVerifyBtnDisabled}
    />
  )
}

实现说明

  • React Native原生的Button组件支持disabled属性,属性值为true时按钮会自动变为不可点击状态,将该属性和你声明的状态变量绑定即可控制按钮可用状态
  • 代码中点击触发逻辑的第一行就更新状态禁用按钮,不管后续接口请求是否成功都不会再响应点击,符合点击一次后自动禁用的需求
  • 若业务允许请求失败后用户重新点击,只需在catch分支中把禁用状态改回false即可

内容的提问来源于stack exchange,提问作者Cli Ad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:18:03