【发布时间】:2021-10-12 03:03:06
【问题描述】:
在 vanilla Javascript 中,我可以像这样在事件监听器中访问“this”关键字:
<body>
<button type="button" onclick="test(this)">Click Me</button>
<script>
function test(t) {
console.log(t); //this
}
</script>
</body>
或者像这样
<body>
<button id="test" type="button">Click Me</button>
<script>
document.getElementById("test").onclick = function () {
console.log(this);
};
</script>
</body>
但是如何在反应事件监听器中使用 'this' 关键字访问 DOM 元素
export default function Button() {
function test() {
console.log(this); //undefined
}
return (
<button onClick={test} id="test" type="button">
Click Me
</button>
);
}
我知道我可以使用“事件”对象访问目标元素。但我很好奇是否可以在反应事件监听器中使用“this”
【问题讨论】:
-
您期望
this是什么?你想解决什么更高层次的问题?为什么不能使用事件目标? -
@charlietfl this = 附加到侦听器的元素。我不想解决任何更高级别的问题。只是好奇。
-
简短的回答是否定的......
this不会绑定到元素 -
@kmoser 感谢您的回复。不。在那个问题中使用了这个,因为他们使用的是类组件而不是功能组件
标签: javascript reactjs