[英]React JS onKeyUp event does not sending data to function
Im trying to create an ajax user search
like linkedin's, so when i type a character from the keyboard i should get results without pressing the enter key.我正在尝试像 linkedin 一样创建
ajax user search
,所以当我从键盘输入一个字符时,我应该在不按回车键的情况下得到结果。
In my input field i have the onKeyUp={sendData(this)} to send the data in the sendData function, and then fetch the results.在我的输入字段中,我有onKeyUp={sendData(this)}来发送 sendData function 中的数据,然后获取结果。
<input type="text" id="userfield" onKeyUp={sendData(this)}/>
function sendData (input){
if (input!=null){
console.log("data:",input)
fetch('/userSearch',{
method:'POST',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({ input: input.value})
})
}
}
My problem is that in the console.log("data:",input)
line i get undefined.我的问题是在
console.log("data:",input)
行中我得到了未定义。 Which means the onKeyUp event sends nothing to the function. Im i missing something?这意味着 onKeyUp 事件不会向 function 发送任何内容。我错过了什么吗?
In React onKeyUp
and event listeners in general expect a function to be passed, and will pass the event
as an argument by default.在 React
onKeyUp
和事件侦听器中,通常期望传递 function,并且默认情况下会将event
作为参数传递。 In your case you want to pass the sendData
function like so:在您的情况下,您希望像这样传递
sendData
function:
<input type="text" id="userfield" onKeyUp={sendData}/>
and then receive the input element like:然后接收输入元素,如:
function sendData (event){
const input = event.target;
// Do stuff with input
}
Also if you are trying to fetch some data you have to handle it somehow.此外,如果您尝试获取一些数据,则必须以某种方式处理它。 You should either add a
.then((result)=>{/* Handle the result */})
to the fetch
call or make sendData
an async
function and then await
the result like:您应该将
.then((result)=>{/* Handle the result */})
添加到fetch
调用或使sendData
成为async
function 然后await
结果,例如:
async function sendData (event){
const input = event.target;
const result = await fetch(/*...*/)
}
Simply you can use简单地你可以使用
<input type="text" id="userfield" onKeyUp={(e)=>sendData(e.target.value)}/>
e.target gives you the element that triggered the event. e.target为您提供触发事件的元素。
e.target.value retrieves the value of that element e.target.value检索该元素的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.