【问题标题】:How to I access DOM element using 'this' keyword in React如何在 React 中使用“this”关键字访问 DOM 元素
【发布时间】: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


【解决方案1】:

传递一个参数以获取事件参数。

例如:

function test(event) {
    console.log(event.target); // returns the element which trigered the event
    console.log(event.currentTarget); // returns the element that the event listener is attached to.
 }

但如果你不想这样做,你也可以在事件内部使用querySelector方法。

   const element = document.querySelector("#test");

【讨论】:

  • 感谢您的回复。我已经在问题中提到我知道如何使用事件对象访问目标元素。我只想知道是否可以在反应事件监听器中使用“this”关键字访问 dom 元素
  • 别以为有办法,这与 jQuery 的绑定方式不同
【解决方案2】:

您可以使用ref 访问 React 中的 DOM 节点。

import React, { useRef } from "react";

function Button() {
  const buttonRef = useRef(null);
  function test() {
    console.log(buttonRef.current); 
  }
  return (
    <button onClick={test} id="test" type="button" ref={buttonRef}>
      Click Me
    </button>
  );
}

在此处阅读有关ref 的更多信息:https://reactjs.org/docs/hooks-reference.html#useref

【讨论】:

  • 感谢您的回复。我正在查看是否存在与香草代码中的“this”关键字等效的反应。原来不是
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 2015-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
相关资源
最近更新 更多