首页 > 解决方案 > 单击时删除数组中的元素并且只接受输入标签中的数字类型?[反应JS]

问题描述

我是前端新手,现在仍在学习这方面的东西。我有两个需要你帮助的斗争,但首先我需要展示代码:

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 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
            value={price}
            placeholder={'Enter price..'}
            onChange={e => setPrice(e.target.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}> đồng x</span>
               </li>
           ))}
       </ul>
    </div>
)
}

export default Content;

所以我正在做一个小应用程序所谓的计算器,在第二个输入标签中,我不知道如何让它只接受数字,以及如何压入跨度标签,特别是按'x',它必须被移除。

请大家帮帮我,谢谢大家!

标签: reactjs

解决方案


如果我猜对了,您想进行第二次输入以仅接受数字吗?您可以将输入类型更改为数字,也可以编写自定义模式

你还想让 span 可点击吗?您可以将onClick事件设置为任何(?)html标签并使其可点击

这是一个例子span

<span 
    className={'delete'} 
    data-index={index}
    onClick={(e)=>{removeThisItem(e)}
> 
    đồng x
</span>

推荐阅读