尝试使用react-keydown组件时出错

时间:2017-05-30 18:55:47

标签: reactjs babeljs react-jsx keydown

我目前正在尝试使用react-keydown组件,如以下文档所示:react-keydown component。我的代码如下:

import React, { PropTypes } from 'react';
import keydown, { Keys } from 'react-keydown';

const propTypes = {
  onNewGame: PropTypes.func.isRequired
};

export default class Home extends React.Component {

  constructor( props ) {
    super( props );
  }

  @keydown( 'enter' )
  submit( event ) {
    console.log('clicked');
  }


render() {
  return (
    <div>
      <div className="img-margin">
        <div className="margin">
          <img alt="" src="/assets/logo/logo_blank.png"/>
        </div>
      </div>
    </div>
  );
}}

Home.propTypes = propTypes;

我得到的错误是:

Module build failed: SyntaxError: Method has decorators, put the decorator plugin before the classes one.

我已经安装了babel-plugin-transform-decorators并将其包含在我的.babelrc中。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

react-keydown仅在transform-decorators-legacy下进行了测试。转换修饰符的解析方式可能有所不同。尝试删除该转换,然后查看是否有效。

答案 1 :(得分:-1)

你正在考虑我认为错误的例子。如果您正在使用类,则必须将装饰器放在类之外。 https://www.npmjs.com/package/react-keydown#for-classes-pass-keydown-events-into-your-component

//Move decorator above class
@keydown
class MyComponent extends React.Component {
  componentWillReceiveProps( { keydown } ) {
    if ( keydown.event ) {
      // inspect the keydown event and decide what to do 
      console.log( keydown.event.which );
    }
  }

  render() {
    return (
      <div>keydown events will only get passed down after this DOM node mounts or is clicked on</div>
    );
  }
}

export default MyComponent;