Enabling submit button button when all inputs is filled?

一曲冷凌霜 提交于 2019-12-11 14:08:54

问题


Entire examples doesn't show simple solution how to keep submit button disabled until all fields is filled up in redux-form.

I tried to use this approach (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);

But this code above doesn't seems to be working. The form doesn't want to re-render even if I force it through subscribe event. It only re-render when pristine or submitting event is triggered. But if I want to re-render myself the form just ignore it. Maybe some flag I missed to re-render manually the form when I need to?


回答1:


Ok, finally the solution has been found: just need to modify parameter pure in reduxForm constructor from true (default) to false

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

And the from will re-render whenever you need.



来源:https://stackoverflow.com/questions/48256410/enabling-submit-button-button-when-all-inputs-is-filled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!