简体   繁体   中英

Programatically change Redux-Form Checkbox Field value

I have a register form. When user accept term of services, he clicks on a button which check the checkbox. When he clicks on decline, this button uncheck the checkbox.

复选框 接受按钮

I read this answer to programmatically change redux-form values . I am able to change any field except checkbox.

Here are my code:

class RegisterContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalTOS: false
    };

    this.accept = this.accept.bind(this);
    this.decline = this.decline.bind(this);
    this.toggleTOSModal= this.toggleTOSModal.bind(this);
  }

  accept() {
    this.props.actions.change("register", "email", "foo42bar"); //This is a working test
    this.props.actions.change("register", "read", true);
    this.toggleTOSModal();
  }
  decline() {
    this.props.actions.change("register", "read", false);
    this.toggleTOSModal();
  }

  // ....

I added this line only to check if email value could be changed:

this.props.actions.change("register", "email", "foo42bar");

电子邮件正在改变...

It works !

Step by step, I tried a lot of options to check , but no one has changed checkbox:

this.props.actions.change("register", "read", "on");
this.props.actions.change("register", "read", true);
this.props.actions.change("register", "read", "1");
this.props.actions.change("register", "read", 1);
this.props.actions.change("register", "read", "true");
this.props.actions.change("register", "read", "a");

In validator, I added some console.error . With manual check or via the accept button, value is true. But Checkbox don't check

edit: My field declaration:

<Field name="read" component={FormCheckBoxGroup} {...fieldProps} onClick={onClickTos} required />

FormCheckBoxGroup:

<FormGroup check>
  <Col sm={{ size: 8, offset: 4 }}>
    <Label check className={className}>
      <Input {...input} type="checkbox" disabled={disabled} required={required} />
      {label}
    </Label>
    {!required && helpBlock && <HelpBlock>{helpBlock}</HelpBlock>}
    {error && <HelpBlockErrors errors={messages} />}
    {children}
  </Col>
</FormGroup>

Have someone an idea?

true/false will only work if you tell redux-form that it's a checkbox. From it's docs:

input.checked : boolean [optional] An alias for value only when value is a boolean. Provided for convenience of destructuring the whole field object into the props of a form element.

Make sure you're declaring your Field correctly

<Field name="accpetTerms" component="input" type="checkbox" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM