我有一个关键字搜索文本框,我想在用户按下 Enter 键时运行搜索功能。但是现在该事件不会被解雇。我的代码如下:
onkeyPress=(e)=>{
if(e.key === "Enter" ||e.charCode === 13||e.keyCode === 13){
console.log('keyword value', this.state.keyword);
this.runSearch();
}
}
...
<input id="search-box" placeholder="Enter a search term..." type="textbox" value={this.state.keyword} onChange={this.onKeywordInputChange} onKeyPress={this.onKeyPress} />
--------下面的工作代码---- https://reactarmory.com/guides/react-events-cheatsheet
handler=(event)=> {
console.log("key:", event.key);
if (event.key==="Enter"){...}
}
<input
id="search-box" type="textbox"
value={this.state.keyword}
onChange={this.onKeywordInputChange}
placeholder='Enter a search term...'
onKeyPress={this.handler}
/>
最佳答案
确保 onKeyPress
在类组件构造函数中:
constructor(props) {
super(props);
this.onKeyPress = this.onKeyPress.bind(this);
}
或者你使用
onKeyPress = (e) => {}
或者您使用功能组件并完全省略 this
https://codesandbox.io/s/crimson-wood-khmg0
function App() {
const onKeyPress = e => console.log(e.nativeEvent);
return (
<div className="App">
<input type="text" placeholder="type something" onKeyPress={onKeyPress} />
</div>
);
}
关于javascript - OnKeyPress 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58401805/