在 React 中显示具有当前默认值的计数器 onChange 输入框

Show counter onChange input box with a current defaultValue in React

如何首先从 API 的数据中获取初始值,然后在用户开始输入或删除文本时更改值?

import React, {useState} from 'react'

const MyInput = () => {
  const [counter, setCounter] = useState(0)

  const initial = dataFromApi.length

  const total = 1000

  const counterChange = (e) => {
    setCounter(initial.length + e.target.value.length)
  }

  return(
    <>{counter}/{total}<input defaultValue={dataFromApi} onChange={counterChange}/></>
  )

}

export default MyInput

https://codesandbox.io/s/compassionate-napier-3nekx?file=/src/App.js

将初始长度传递给 useState 挂钩

const initial = dataFromApi.length
const [counter, setCounter] = useState(initial)

如果您希望 API 数据发生变化,您可以使用 useEffect 挂钩在 API 数据发生变化时重置长度状态

useEffect(() => {
  setCounter(dataFromApi.length);
}, [dataFromApi.length]);

如果您想显示输入文本的当前长度,则无需在 onChange 处理程序中添加初始值

setCounter(e.target.value.length)