【问题标题】:How to target object id from array of objects using onClick [duplicate]如何使用onClick从对象数组中定位对象ID [重复]
【发布时间】:2020-10-26 23:02:24
【问题描述】:

这是我的代码 - 正如你所看到的,我刚刚开始使用 React.js 和一般的编程。在这个我试图创建一个简单的待办事项列表,我希望能够通过单击列表项之一从中删除一些项目。我知道我的 onClick 中有一些错误/缺少代码,但无法确定如何定位正确的 id 来处理 onDeleteHandler...非常感谢 ofc。

const App = () => {

const [input, setInput] = useState('')
const [index, setIndex] = useState([])

const id = Date.now()

const onSubmitHandler = (event) => {
    event.preventDefault()

    if (input.length > 0)
        setIndex([...index, { input, id }])
    else
        alert("Write a proper activity, please!")

    setInput('')
}

const onChangeHandler = (event) => {
    setInput(event.target.value)
}

const onDeleteHandler = (id) => () => {
    let xxx = index.filter(item => item !== id)
    setIndex(xxx)
    console.log(xxx)
}


return (
    <div>
        <form className="App" onSubmit={onSubmitHandler}>
            <p>MY REACT TO DO LIST</p>
            <label>Activity : </label>
            <input type="text" value={input} onChange={onChangeHandler}></input>
            <input type="submit"></input>
        </form>
        <ul>
            {index.map((item, id) => <li key={id} onClick={onDeleteHandler}>{item.input}</li>)}
        </ul>
    </div>
)

}

【问题讨论】:

  • 你有一个咖喱处理程序,所以在附加处理程序时只需传递 id,即onClick={onDeleteHandler(id)}。另外请注意,由于您使用数组索引作为反应键 and 改变数组,因此您可能会产生意想不到的副作用。使用更好的反应键,被映射的元素独有的东西,比如 guid。

标签: javascript reactjs arraylist


【解决方案1】:

改变

const onDeleteHandler = () => {
    console.log(id)
}

const onDeleteHandler = (id) => {
    console.log(id)
}

然后将onClick={onDeleteHandler}改为onClick={() =&gt; onDeleteHandler(id)}

看看这个:https://upmostly.com/tutorials/pass-a-parameter-through-onclick-in-react 了解更多信息

【讨论】:

猜你喜欢
  • 2021-08-20
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
  • 2020-10-01
相关资源
最近更新 更多