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

ReactJS如何实现点击删除数组元素与input框仅接受数字输入

问题1 价格输入框仅允许输入数字实现方式

给第二个input做两层限制即可:

  • 原生属性层面添加type="number",浏览器会默认拦截非数字输入,移动端也会自动唤起数字键盘
  • onChange事件中增加字符过滤逻辑,避免用户手动粘贴非数字内容,这里我们只保留数字和小数点适配价格场景

问题2 点击x删除对应商品实现方式

新增删除处理函数,接收要删除的商品下标为入参,使用数组filter方法过滤掉对应下标的元素后更新products状态即可,再给span标签绑定点击事件触发该函数。


修改后完整代码如下:

import React, {useState, useRef, useMemo} from 'react'

function Content() {
   const [name, setName] = useState('')
   const [price, setPrice] = useState('')
   const [products, setProducts] = useState([])
   const ref = useRef()

   const handleSubmit = () => {
       setProducts([...products, {
           name,
           price: Number(price)
       }])
       setName('')
       setPrice('')
       ref.current.focus()
   }

   // 新增删除处理函数
   const handleDelete = (delIndex) => {
       setProducts(prev => prev.filter((_, index) => index !== delIndex))
   }

   const total = useMemo(() => {
       console.log('Calculating..')
       const calculator = products.reduce((init, currentValue) => {
           return init + currentValue.price
       }, 0)
       return calculator;
   }, [products])

   return (
       <div style={{padding: '10px 32px'}}>
          <input
               ref={ref}
               value={name}
               placeholder={'Enter name..'}
               onChange={e => setName(e.target.value)}
          />
          <br />
          <input
               type="number"
               value={price}
               placeholder={'Enter price..'}
               onChange={e => {
                   // 输入过滤,只保留数字和小数点
                   const value = e.target.value.replace(/[^0-9.]/g, '')
                   setPrice(value)
               }}
          />
          <br />
          <button 
               children={'Add'}
               onClick={handleSubmit}
          />
          <h3>Total :{total}</h3>
          <ul>
              {products.map((product, index) => (
                  <li key={index}>
                      {product.name} - {product.price} 
                       <span 
                           className={'delete'} 
                           data-index={index}
                           onClick={() => handleDelete(index)}
                       > đồng x</span>
                  </li>
              ))}
          </ul>
       </div>
   )
}

export default Content;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:36:05