如何在特定按键上提交 redux-form?

How to submit redux-form on specific keypress?

我有一个 redux 形式的集成 React 组件(redux 形式 v7.0.1),我试图在用户同时按下 commandenter 时触发提交。

我可以成功检查是否按下了两个键,但是我无法使用 handleSubmit 通过表单外的函数提交表单。

如何将 handleSubmit 与我的 onSubmit 函数一起使用?

方法:

constructor(props){
  super(props);

  this.state = {
    commandKeyPressed: false
  }

  this.onSubmit = this.onSubmit.bind(this);
  this.handleKeyDown = this.handleKeyDown.bind(this);
}

onSubmit(values) {
  console.log(values); // does not log anything
}

handleKeyDown(e) {
  if (e.keyCode === 91){
    this.setState({ commandKeyPressed: true });
  }

  // [enter] key is pressed after command.
  // the keyCode is stored in component state to 
  // check if it was pressed

  if (e.key === 'Enter') {
    e.preventDefault();

    if (this.state.commandKeyPressed) {
      // logs 'trying to submit', but does not call this.onSubmit
      console.log(
        'trying to submit', this.props.handleSubmit(this.onSubmit)
      ); 
    }
  }
} 

渲染方法:

return (
  <div>
    <div className="ama-submit-field reply-container">
      <form ref='commentReplyRef' onSubmit={handleSubmit(this.onSubmit)}>
        <Field
          name="commentReply"
          keyDown={e => this.handleKeyDown(e)}
          keyUp={e => this.handleKeyUp(e)}
          type="input"
          component={myCustomField}
          label={text}>
        </Field>
      </form>
    </div>
  </div>
);

我找到了解决方法。我认为这是一个技巧,但对我有用。

当我创建表单时,我通过在 reduxForm() 选项中指定 onSubmithandleSubmit() return values:

const CommentForm = reduxForm({
  form: 'Comment',
  onSubmit: values => values,
  validate
})(Comment);

export default CommentForm;

我将 validate 更改为 return 一个带有输入字段错误键的对象:

function validate(values){
  const errors = {};

  if (!values.commentReply){
    errors.commentReply = {
      error: true,
      text: 'Please enter a question.'
    };
  }

  return errors;
}

然后,在handleKeyDown

handleKeyDown(e) {
  if (e.keyCode === 91) {
    this.setState({commandKeyPressed: true});
  }

  // [enter] key is pressed after command.
  // keyCode is stored in component state to
  // check if it was pressed

  if (e.key === 'Enter') {
    e.preventDefault();

    if (this.state.commandKeyPressed) {
      const values = this.props.handleSubmit();

      if (!values.commentReply.hasOwnProperty('error') {
        this.onSubmit(values);
      }
    }
  }

这让我可以在按键时触发我的提交功能。

我认为更好的做法是将所有提交逻辑移动到 reduxForm 属性,但是我的 React [=15] 中有很多 state-specific 行为=]函数。