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

如何基于form?.hasErrors布尔值动态切换按钮type为submit或button

你的代码存在逻辑不一致问题:btnType 函数中将 form?.hasErrors 作为布尔属性读取判断,但是在 onClick 绑定中你又将其作为方法调用 form?.hasErrors(),两处逻辑不一致会直接导致按钮type属性切换不符合预期。

修正方案

方案1:内联判断(代码更精简)

return (
  <>
    <StyledButton
      onClick={!form?.hasErrors() ? handleShowModal : undefined}
      type={form?.hasErrors() ? "submit" : "button"}
    >
      Search
    </StyledButton>
  </>
);

方案2:保留独立btnType函数,统一判断逻辑

const btnType = () => {
  // 统一改为调用hasErrors()方法,和onClick处逻辑保持一致
  if (form?.hasErrors()) {
    return "submit";
  }
  return "button";
};

return (
  <>
    <StyledButton
      onClick={!form?.hasErrors() ? handleShowModal : undefined}
      type={btnType()}
    >
      Search
    </StyledButton>
  </>
);

如果 hasErrors 本身是布尔属性而非方法,统一将两处的调用括号()删除即可,核心保证两处对hasErrors的取值逻辑完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:06:02