[英]How to access DOM element's attributes and value inside an event handler function in React?
我的渲染功能是
<input type="text" id="search" data-id={form.id} value={form.name} placeholder= "Search..." name="id" onKeyUp={this.keyUpFn}"/>
我的keyUpFn
函数是
keyUpFn(e){
var textInput = document.getElementById('search');
value1 = textInput.getAttribute('data-id')
value2 = e.getAttribute('data-id')
console.log(value1 )
console.log(value2 )
}
由于未定义getAttribute
因此两个控制台值都会给出错误。 我如何在 React 中解决这个问题?
您可以从 Event 目标对象中获取数据。 这是代码的样子
keyUpFn(e){
console.log(e.target.getAttribute('data-id'));
console.log(e.target.value);
}
您实际上可以通过访问获取从您的函数中的事件 (e) 请求的数据
event.currentTarget.dataset.paramater;
keyUpFn(e) {
e.currentTarget.dataset.id
}
您可以使用 getElementsByClassName(或 id、name 等)、querySelectorAll、focus。 前两个返回所有有效元素的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.