试图在react.js中实现键绑定。做了一些研究,但仍然想知道什么是最干净的方法。例如,
if (event.keyCode == 13 /*enter*/) {
function()
}
if (event.keyCode == 27 /*esc*/) {
anotherfunction()
}
答案 0 :(得分:9)
当安装和卸载组件时,我最终绑定了keydown事件:
...
componentDidMount: function() {
$(document.body).on('keydown', this.handleKeyDown);
},
componentWillUnMount: function() {
$(document.body).off('keydown', this.handleKeyDown);
},
handleKeyDown: function(event) {
if (event.keyCode == 13 /*enter*/) {
this.okAction();
}
if (event.keyCode == 27 /*esc*/) {
this.cancelAction();
}
},
render: function() {
return this.state.showDialog ? (
<div className="dialog" onKeyDown={this.handleKeyDown}>
...
这可能是更好的方法。该函数用作对话框组件的一部分:https://github.com/changey/react-dialog
答案 1 :(得分:1)
第1步:在构造函数中定义
constructor(props) {
super(props);
this.state = {
}
this.handleEnterKeyPress = this.handleEnterKeyPress.bind(this)
}
第2步:将其写入渲染方法
render() {
return (
<input className ="pageText" type="text" value= "value" onKeyPress = {this.handleEnterKeyPress} />
)
}
步骤3:在类
中编写相应的函数handleEnterKeyPress(e) {
if (e.charCode == 13) {
// your code
}
}
答案 2 :(得分:0)
这是我的搜索组件,请查看onSearch函数。我没有使用键盘绑定来完成转义键清除输入和散焦。
import React from "react"
import _debounce from "lodash.debounce"
import "./stylesheets/search"
export default class Search extends React.Component {
displayName = "Search"
static propTypes = {
bucketName: React.PropTypes.string,
placeholder: React.PropTypes.string,
onSearchUpdated: React.PropTypes.func,
}
state = {
search: "",
placeholder: "Search",
bucketName: "",
}
componentWillMount() {
this.delayedCallback = _debounce((event) => {
let search = event.target.value
this.setState({
search,
})
this.props.onSearchUpdated(search, this.props.bucketName)
})
}
onSearch = (event) => {
if (event.keyCode === 27) {
event.target.value = ''
this.refs.input.blur()
} else {
this.refs.input.focus()
}
event.persist()
this.delayedCallback(event)
}
render() {
return (
<div className="search">
<div className="row">
<div className="col-xs-12 search__container form-group">
<input
ref="input"
className="form-control search__field"
placeholder={this.props.placeholder}
name="search__field"
id="search__field"
type="text"
onKeyDown={this.onSearch}
/>
</div>
</div>
</div>
)
}
}
答案 3 :(得分:-3)
还没有足够的代表对您的回答发表评论,但我想提出改进意见。
在绑定/取消绑定时,尝试使用事件命名空间。这在将事件绑定到正文时尤其重要,因为它允许您在不中断任何其他相同类型的绑定的情况下取消绑定:
见:
https://css-tricks.com/namespaced-events-jquery/
componentDidMount: function() {
$(document.body).on('keydown.awesomeNamespaceName', this.handleKeyDown);
},
componentWillUnMount: function() {
$(document.body).off('keydown.awesomeNamespaceName', this.handleKeyDown);
},
handleKeyDown: function(event) {
if (event.keyCode == 13 /*enter*/) {
this.okAction();
}
if (event.keyCode == 27 /*esc*/) {
this.cancelAction();
}
},