javascript - OnKeyPress 不触发

标签 javascript reactjs

我有一个关键字搜索文本框,我想在用户按下 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/

相关文章:

javascript - Google 可视化 - AnnotatedTimeLine 上的多行

javascript - 监听 Sencha Touch 上的启用/禁用事件

javascript - react : Filter multidimensional array object by value in component

reactjs - 后退按钮在 React 中显示空白页面

reactjs - 如何将 jsconfig.json 添加到现有的 vscode 项目而不破坏它

javascript - CLI 移至单独的包 : webpack-cli

javascript - CSS:将悬停动画与其他类相关动画分开

javascript - Node.js 请求随机开始挂起,直到服务器重启才会清除

javascript - 如何阻止 IE8 或更低版本访问某个网站?

javascript - 用对象声明的样式化组件中的媒体查询