自定义金额字段配置问题:输入值异常求助(附React代码)
问题分析与解决
核心问题
问题根源在onChangeSuma函数:React的useState更新是异步的,你调用setYourPrice(e.target.value)后,立刻用旧的yourPrice值更新price,导致price永远慢一拍——输入单个数字时,price拿到初始空值;输入多位数字时,price总是缺失最后一位。另外handleSubmit里多余调用clickEvent()毫无意义,无参数传入时只会直接返回。
修复代码
修改后的JS逻辑
const [price, setPrice] = useState(0) const [yourPrice, setYourPrice] = useState('') const handleSubmit = (e) => { e.preventDefault() console.log(price) setYourPrice('') } function clickEvent (e, v){ e.preventDefault() // 阻止按钮默认提交行为 if(v === 5 || v === 10 || v === 15) { setPrice(v) setYourPrice('') } } const onChangeSuma = e => { const inputValue = e.target.value setYourPrice(inputValue) // 直接用最新输入值更新price,不依赖异步更新后的yourPrice setPrice(inputValue) }
表单代码
<form onSubmit={handleSubmit}> <div className="d-flex justify-content-between"> <button className={`${price === 5 ? 'active' : 'noActive'}`} onClick={e => clickEvent(e, 5)} > $5 </button> <button className={`${price === 10 ? 'active' : 'noActive'}`} onClick={e => clickEvent(e, 10)} > $10 </button> <button className={`${price === 15 ? 'active' : 'noActive'}`} onClick={e => clickEvent(e, 15)} > $15 </button> </div> <div className="col text-center pt-1 fs-5 m-1 py-2"> <label>Your Price</label> <input type="number" className={yourPrice ? 'active' : 'noActive'} placeholder='$ Other' id="inputID" autoFocus={!!yourPrice} // 转为布尔值,确保属性值合法 value={yourPrice} onChange={onChangeSuma} /> </div> <button className='btn btn-secondary border-0 rounded-0 py-2 w-100' type='submit'>SUBMIT</button> </form>
额外优化说明
- 给
clickEvent添加e.preventDefault(),避免点击预设金额按钮时触发表单提交。 autoFocus需传入布尔值,用!!yourPrice确保空字符串时为false,有输入值时为true。
内容的提问来源于stack exchange,提问作者Peret
相关产品推荐
相关产品推荐

