[英]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 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.