最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - key binding in react.js - Stack Overflow

programmeradmin9浏览0评论

was trying to implement key binding in react.js. did some research, but still wondering what's the cleanest way to do it. For example,

if (event.keyCode == 13 /*enter*/) {
  function()
}
if (event.keyCode == 27 /*esc*/) {
  anotherfunction()
}

was trying to implement key binding in react.js. did some research, but still wondering what's the cleanest way to do it. For example,

if (event.keyCode == 13 /*enter*/) {
  function()
}
if (event.keyCode == 27 /*esc*/) {
  anotherfunction()
}
Share Improve this question asked Apr 9, 2015 at 23:46 changeychangey 19.6k9 gold badges31 silver badges37 bronze badges 1
  • stackoverflow./questions/27827234/… maybe it will help you – hod caspi Commented Nov 10, 2016 at 10:05
Add a ment  | 

4 Answers 4

Reset to default 11

I ended up binding the keydown event when the ponent mounted and unmounted:

...

ponentDidMount: function() {
  $(document.body).on('keydown', this.handleKeyDown);
},

ponentWillUnMount: 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}>

...

There's probably a better way to do this. The function is used as a part of a dialog ponent: https://github./changey/react-dialog

step 1 : Define it in constructor

  constructor(props) {
    super(props);

    this.state = {        
    }
    this.handleEnterKeyPress = this.handleEnterKeyPress.bind(this)
  }

step 2 : Write it in render method

 render() {   
            return (             
                   <input className ="pageText" type="text" value= "value" onKeyPress = {this.handleEnterKeyPress} />                       
            )
          }

step 3 : write the respective function in the class

handleEnterKeyPress(e) {
    if (e.charCode == 13) {
      // your code
    }
  }

Here is my search ponent, please take a look at the onSearch function. I'm using no keyboard binding to acplish the escape key clearing input and defocusing.

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: "",
  }

  ponentWillMount() {
    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>
    )
  }
}

Don't yet have enough rep to ment on your answer yet, but I would like to suggest an improvement.

Try using event namespacing when you bind/unbind these. This is especially important when binding events to the body, as it allows you to unbind without disrupting any other bindings of the same type:

See:
https://css-tricks./namespaced-events-jquery/

ponentDidMount: function() {
  $(document.body).on('keydown.awesomeNamespaceName', this.handleKeyDown);
},

ponentWillUnMount: 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();
  }
},
发布评论

评论列表(0)

  1. 暂无评论