简体   繁体   English

如何在 React 的事件处理函数中访问 DOM 元素的属性和值?

[英]How to access DOM element's attributes and value inside an event handler function in React?

My render function is我的渲染功能是

<input type="text" id="search" data-id={form.id} value={form.name} placeholder= "Search..." name="id" onKeyUp={this.keyUpFn}"/>

and my keyUpFn function is我的keyUpFn函数是

keyUpFn(e){
    var textInput = document.getElementById('search');
    value1 = textInput.getAttribute('data-id')
    value2 = e.getAttribute('data-id')
    console.log(value1 )
    console.log(value2 )
}

Both console value gives error as getAttribute is not defined.由于未定义getAttribute因此两个控制台值都会给出错误。 How can I solve this in React?我如何在 React 中解决这个问题?

You can get the data from the Event target object.您可以从 Event 目标对象中获取数据。 This is how the code would look这是代码的样子

keyUpFn(e){
    console.log(e.target.getAttribute('data-id'));
    console.log(e.target.value);
}

You can actually get the data requested from the event (e) in your function by accessing您实际上可以通过访问获取从您的函数中的事件 (e) 请求的数据

event.currentTarget.dataset.paramater;

keyUpFn(e) {
  e.currentTarget.dataset.id
}

You can use getElementsByClassName (or id, name etc.), querySelectorAll, focus.您可以使用 getElementsByClassName(或 id、name 等)、querySelectorAll、focus。 First two returns an array of all valid elements.前两个返回所有有效元素的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM