填写完所有输入后启用提交按钮按钮?

时间:2018-01-15 03:02:00

标签: node.js typescript react-redux redux-form react-redux-form

整个examples没有显示简单的解决方案如何在redux-form填写完所有字段之前停止提交按钮。

我尝试使用这种方法(TypeScript):

import * as React from 'react';
import * as reduxForm from 'redux-form';

export interface Props extends reduxForm.InjectedFormProps {}

let passedUsername = false;
let passedPassword = false;

const required = (value: string, callback: (passed: boolean) => void) => {
  console.info(`PERFORM REQUIRED FIELD CHECK FOR ${value}`);
  if  (value && value.trim().length > 0) {
      callback(true);
  } else {
    callback(false);
  }
};

const usernameRequired = (value: string) => {
  required(value, passed => { passedUsername = passed; });
};
const passwordRequired = (value: string) => {
  required(value, passed => { passedPassword = passed; });
}; 

const isPassed = () => {
  console.info(`USER PASSED: ${passedUsername}`);
  console.info(`PASSWORD PASSED: ${passedPassword}`);
  const result = passedUsername && passedPassword;
  console.info(`PASSED: ${result}`);
  return result;
};

const LoginForm = ({handleSubmit, pristine, submitting}: Props) => (
    <form onSubmit={handleSubmit}>
    <div>
      <label>Username </label>
      <reduxForm.Field
            name="username"
            component="input"
            type="text"
            validate={[usernameRequired]}
            placeholder="Username" 
      />
      <br/>
      <label>Password </label>
       <reduxForm.Field
            name="password"
            component="input"
            type="password"
            validate={[passwordRequired]}
            placeholder="Password" 
       />
    </div>
    <br/>
    <div>
        <button type="submit" disabled={!isPassed()}>
        <i className="fa fa-spinner fa-spin" style={{visibility: (submitting) ? 'visible' : 'hidden'}}/>
        &nbsp;
        <strong>Login</strong>
        </button>
      </div>
    </form>
);

export default reduxForm.reduxForm({
  form: 'login'
})(LoginForm);

但是上面的代码似乎并没有起作用。即使我通过订阅事件强制它,表单也不想重新渲染。它仅在触发原始或提交事件时重新呈现。但是,如果我想重新渲染自己,那么就忽略它。也许有些旗帜在我需要的时候错过了手动重新渲染表单?

1 个答案:

答案 0 :(得分:0)

好的,最后找到了解决方案:只需要在reduxForm构造函数中将参数 pure true (默认)修改为 false < / p>

export default reduxForm.reduxForm({
  form: 'login',
  pure: false
})(LoginForm);

当你需要时,from会重新渲染。