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

如何手动更新Chakra UI useNumberInput的值?是否需弃用该Hook?

问题描述

我目前正在使用Chakra UI的useNumberInput Hook开发自定义数字输入组件。当API调用失败时,我需要手动更新useNumberInput返回的输入值,将其设置为Redux中存储的最新值。请问能否在继续利用useNumberInput功能的前提下实现该需求?还是我应该直接弃用useNumberInput,自行实现解决方案?

代码示例

function HookUsage() {
  const { getInputProps, getIncrementButtonProps, getDecrementButtonProps } =
    useNumberInput({
      step: 0.01,
      defaultValue: 1.53,
      min: 1,
      max: 6,
      precision: 2,
    })

  const inc = getIncrementButtonProps()
  const dec = getDecrementButtonProps()
  const {
    // 这是我想要手动更新或重置的值
    value,

    ...inputProps
  } = getInputProps()

  return (
    <HStack maxW='320px'>
      <Button {...inc}>+</Button>
      <Input value={value} {...inputProps} />
      <Button {...dec}>-</Button>
    </HStack>
  )
}

回答

完全不用弃用useNumberInput,用受控模式就能搞定,还能保留它所有的步进、精度校验这些功能。

具体操作步骤:

  • 从Redux里拿到你要的最新有效值,作为输入的受控数据源
  • 给useNumberInput传value和onChange参数,替换原来的defaultValue
  • API调用失败时,直接更新Redux里的值,useNumberInput会自动同步这个变化,输入框的值就会重置回去

修改后的代码示例

import { useSelector, useDispatch } from 'react-redux';
// 替换成你实际的action creator
import { updateNumberValue } from './redux/actions';

function HookUsage() {
  const dispatch = useDispatch();
  // 从Redux获取当前显示的值
  const currentValue = useSelector(state => state.yourModule.numberValue);
  // API失败时要回滚到的有效值
  const validBackupValue = useSelector(state => state.yourModule.validNumberValue);

  const { getInputProps, getIncrementButtonProps, getDecrementButtonProps } =
    useNumberInput({
      step: 0.01,
      // 用Redux的值作为受控值
      value: currentValue,
      onChange: (newVal) => {
        // 用户操作输入框/加减按钮时,同步更新Redux
        dispatch(updateNumberValue(newVal));
      },
      min: 1,
      max: 6,
      precision: 2,
    })

  // 模拟API调用失败后的重置逻辑
  const handleApiFailReset = () => {
    // 把Redux的值设回备份的有效值,输入框会自动同步
    dispatch(updateNumberValue(validBackupValue));
  }

  const inc = getIncrementButtonProps()
  const dec = getDecrementButtonProps()
  const { value, ...inputProps } = getInputProps()

  return (
    <HStack maxW='320px'>
      <Button {...inc}>+</Button>
      <Input value={value} {...inputProps} />
      <Button {...dec}>-</Button>
      {/* 测试用的重置按钮 */}
      <Button onClick={handleApiFailReset}>API失败重置</Button>
    </HStack>
  )
}

核心逻辑就是:useNumberInput支持受控模式,外部传value的话,Hook就不会自己维护内部状态了,完全跟着你给的value走。API失败时只要更新Redux里的value,输入框就会自动变回你要的数值,同时加减按钮、精度限制这些功能都还能用,没必要自己造轮子。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:40:16