I am learning React and doing the Todo list practice these days, here is my code:
import React, {useState} from 'react'
export default function App() {
const[test, setTest] = useState('')
const[list, setList] = useState(['aa','bb','cc'])
const handleChange = (evt) =>{
setTest(evt.target.value)
}
const handleAdd = () =>{
setList([...list, test])
setTest('')
}
const handleDelete = (index) =>{
var newlist = [...list]
newlist.splice(index,1)
setList(newlist)
}
return (
<div>
<input onChange={handleChange} value={test}/>
<button onClick = {handleAdd}>add</button>
<ul>
{list.map((item,index)=>
<li key={index}>
{item}
<button onClick={()=>{
handleDelete(index)
}}>delete</button>
</li>)}
</ul>
</div>
)
}
I know it is a stupid question but I was so confused that why I can not write the last onClick function like this:
<button onClick={handleDelete(index)}>delete</button>
what is the role of the anonymous function?
Thanks for your patience.