reactjs 如何手动更新输入值,而使用脉轮用户界面useNumberInput挂钩

prdp8dxp  于 2023-03-12  发布在  React
关注(0)|答案(1)|浏览(110)

我目前正在使用脉轮用户界面useNumberInput挂钩的自定义数字输入组件。我需要能够更新由useNumberInput返回的输入值手动在事件中,我的API调用失败,以便它可以设置为最后一个值存储到Redux。有什么方法可以做到这一点,同时仍然利用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 {
    // This is the value I want to be able to update or reset manually
    value,

    ...inputProps
  } = getInputProps()

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

从脉轮UI文档中提取上述内容:

  • https://chakra-ui.com/docs/components/number-input/usage#create-a-mobile-spinner

在这种情况下,放弃useNumberInput并构建自己的解决方案是否更好?

x8diyxa7

x8diyxa71#

function HookUsage(props: UseNumberInputProps) {
  const { getInputProps, getIncrementButtonProps, getDecrementButtonProps } = useNumberInput(props)

  const inc = getIncrementButtonProps()
  const dec = getDecrementButtonProps()
  const {
    // This is the value I want to be able to update or reset manually
    value,

    ...inputProps
  } = getInputProps()

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

const Usage = () => {
  const props = {
    step: 0.01,
    min: 1,
    max: 6,
    precision: 2,
  }
  const [value, setValue] = useState(1.53)
  return <VStack>
    <HookUsage value={value} {...props} />
    <Button onClick={() => setValue(2.23)}>update to 2.23</Button>
  </VStack>
}

相关问题