我是前端的新手,现在仍在学习这方面的知识。我有两个困难需要你的帮助,但首先我需要显示代码:
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;
所以我正在做一个叫做计算器的小应用程序,在第二个输入标签中,我不知道如何使它只接受数字,以及如何按下span标签,特别是按下"x",它必须被删除。
请帮帮我,谢谢大家!
如果我做对了,你想进行第二次输入,只接受数字吗?然后你可以将输入类型更改为数字,也可以编写自定义模式
你还想让span可以点击吗?您可以将onClick
事件设置为任何(?(html标签,并使其可点击
以下是span
的示例
<span
className={'delete'}
data-index={index}
onClick={(e)=>{removeThisItem(e)}
>
đồng x
</span>
对于第二个输入,您可以在第二个input标记中添加type="number
。
<input
type="number"
value={price}
placeholder={'Enter price..'}
onChange={e => setPrice(e.target.value)}
/>
要删除特定的产品,可以使用filter
函数来过滤产品数组。
<span className={'delete'} data-index={index} ><button onClick={() => handleDelete(index)} đồng x</button></span>
然后在handleDelete(index(中使用filter
;