【发布时间】:2020-10-11 02:08:30
【问题描述】:
当按钮被点击时,它会保持焦点,所以如果按下回车键或空格键,它就会被视为点击,但我需要它只能在鼠标点击时工作
【问题讨论】:
当按钮被点击时,它会保持焦点,所以如果按下回车键或空格键,它就会被视为点击,但我需要它只能在鼠标点击时工作
【问题讨论】:
如果您只希望一个按钮在鼠标单击时起作用,那么您可以尝试使用任何鼠标事件而不是使用 onClick 事件。
<button onMouseDown={(event) => console.log(event)}> Button </button>
在您的情况下,您应该使用 onMouseDown 事件。 它只会在单击鼠标而不是任何按键时触发。
【讨论】:
您可以在按钮功能中添加一个 if 检查以查看按下了哪个键,除非使用鼠标单击它,否则什么也不做。
const onButtonClick = (event) =>{
//32 is for space-bar
//13 is for enter
if(event.keyCode === 32){
//leave blank so when space is used to press the button it wont do anything
}else if(event.keyCode === 13){
//leave blank so when enter is used to press the button it wont do anything
}else{
//add what you want to do when button is clicked here
//this runs when the button is not pressed using enter or space
}
}
在您的反应按钮组件上:
<button onClick={ onButtonClick }>My Button</button>
【讨论】: