在提交之前计算 redux 表单中的字符

Counting the character in a redux form before submitting

我正在尝试在输入框下方添加一个字符计数器。类似于 Twitter 在其输入框上的内容:

我将 React 和 Redux 与 ReduxForm 一起使用,并尝试遵循本指南 Overview: We’re Going to Build a “Tweet Box”,但它不使用 Redux。 我也尝试过使用 action 和 reducer 将其置于状态,但这似乎与输入框混淆,并且不允许输入任何内容。

最终目标是添加字符数并在输入任何内容之前禁用提交按钮。 如果有人对如何最好地解决这个问题有任何建议,我将不胜感激。

组件代码如下:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import {reduxForm} from 'redux-form';

import * as actions from 'Actions';

class PostQuestionLD extends Component {

  handleFormSubmit({content}) {
    this.props.postQuestionLD({content});
  }

  render() {
    const { handleSubmit, fields: { content }} = this.props;
    return (
      <div>
        <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
          <fieldset className = "form-group" >
            <lable >Question: < /lable> <input {...content} className = "form-control" / >
          </fieldset>
          <button action = "submit" className = "btn btn-primary" > Ask it... </button>
        </form>
        </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    errorMessage: state.questions.error
  }
}

export default reduxForm({
    form: 'postquestion',
    fields: ['content']
}, mapStateToProps, actions)(PostQuestionLD);

好吧,由于需要三元来处理 undefined 情况,我会将长度分配给一个变量,然后执行如下操作:

render() {
  const { handleSubmit, fields: { content } } = this.props
  const length = content.value ? content.value.length : 0
  return (
    <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
      // fieldset here
      <div className="count">{length}</div>
      <button 
        type="submit" // type, not action
        className="btn ban-primary"
        disabled={length < 1 || length > 140}>Ask it...</button>
    </form>
  )
}

这是实现目标的最短路径。理想情况下,您会使用 redux-form 的内置同步验证在超过字符限制时显示警告,并使用 disabled={this.props.invalid} 禁用按钮。在Synchronous Validation Example.

中查看username的长度是如何控制的

确保 handleFormSubmit returns 一个承诺。