我有一个关键字搜索文本框,我想runSearch功能,当用户按下回车键。但是现在这个事件还没有被触发。我的代码如下:
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}
/>发布于 2019-10-16 04:03:09
确保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>
);
}发布于 2019-10-16 08:25:17
我已经更新了一份工作代码。我不知道为什么老代码不能工作。
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}
/>https://stackoverflow.com/questions/58401805
复制相似问题