我有一个 react 组件,由一个输入框、一个按钮和一个最初隐藏的结果框组成。有一个函数可以对 REST API 进行异步调用,获取数据,并将其显示在结果框中(使其可见)。我希望在单击按钮或按 Enter 键时调用该函数。
对于按钮点击,我有:
<button onClick={this.myFunc}>
对于输入键,我有:
<input onKeyUp={this.keyHandler}>
keyHandler = (e) => {
if(e.key === "Enter"){ //tried keycode too
this.myFunc(); }}
<小时/>
我有一个状态变量 isResultLoaded,它设置结果框的可见性,即当 myFunc 从 API 获取结果时,isResultLoaded 设置为 true,这使得结果框可见。
问题:当我单击按钮时,结果框完美显示。但是当我按下回车键时,结果被加载,并且 isResultLoaded 也设置为 true (我将其记录在控制台上),但结果框仍然没有出现。
style={{ visibility: this.state.isResultLoaded ? "visible" : "hidden" }} // For result box
为什么会有两种不同的行为?我该如何解决这个问题?
更新: myFunc() 中有一行重点关注结果框,这导致了此问题。在评论该行时,Keydown 和 Mouseclick 都工作正常。但我需要这条线来实现一个功能。
document.getElementById("result-box").focus(); //tabindex is set to 0
有什么解决办法吗?
最佳答案
这是一个代码
使用onkeypress
,这样它就能正常工作
function keyHandler(e){
if(e.key === "Enter"){ //tried keycode too
myFunc();
}
}
function myFunc(){
console.log('running...')
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button onClick="myFunc()">test</button>
<input onkeypress="keyHandler(event)">
</body>
</html>
关于javascript - Keydown 和 Mouseclick 调用相同的函数但行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58946683/