gpt4 book ai didi

javascript - 在 react 中传递按钮的 'this'

转载 作者:行者123 更新时间:2023-11-28 05:10:21 25 4
gpt4 key购买 nike

因此,要向按钮添加功能,我们通常会这样做

<button onClick={this.delete_this.bind(this)}>clickable</button>

但是如果我也想传递按钮的“this”,那么我可以使用它在过滤器函数中删除自身,该怎么办?

例如:

function delete_this(button)
//button_array defined elsewhere
return button_array.filter( (item) => item != button);

我应该怎样做呢?

最佳答案

首先,不要在render中使用bind,这对性能不利,并且在大多数情况下shouldComponentUpdate会失败。而是在 class constructor 中执行此操作。

<button onClick={this.delete_this}>clickable</button>

现在您可以使用:

  • this 访问组件
  • event.target 访问按钮
<小时/>
function delete_this(event) {
// event has all kinds of cool stuff, check it out
console.log(event)

// current React component (class)
console.log(this)
}

关于javascript - 在 react 中传递按钮的 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41435081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com