【问题标题】:Programatically change Redux-Form Checkbox Field value以编程方式更改 Redux-Form 复选框字段值
【发布时间】:2019-03-11 18:19:24
【问题描述】:

我有一个注册表单。当用户接受服务条款时,他点击一个选中复选框的按钮。当他点击拒绝时,此按钮取消选中复选框。

我读过this answer to programmatically change redux-form values。我可以更改除复选框以外的任何字段。

这是我的代码:

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();
  }

  // ....

我添加此行只是为了检查是否可以更改电子邮件值:

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

有效!

一步一步,我尝试了很多选项来检查,但没有人改变复选框:

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");

在验证器中,我添加了一些 console.error 。通过手动检查或通过接受按钮,值为 true。但是 Checkbox 不勾选

编辑:我的字段声明:

<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>

有人有想法吗?

【问题讨论】:

    标签: javascript reactjs redux-form


    【解决方案1】:

    true/false 只有在你告诉 redux-form 它是一个复选框时才会起作用。来自它的文档:

    input.checked : 布尔值 [可选] 仅当 value 是布尔值时 value 的别名。提供方便将整个字段对象解构为表单元素的道具。

    确保您正确地声明了您的Field

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

    【讨论】:

    • 非常感谢!我编辑了您的答案,因为我在子组件中指定了类型。还不够,我还得在Field中指定。
    • Redux-Form 充满了这样的好东西。在我注意到这一点之前,我无法告诉你我经历了多少头部撞击。 :)
    • 由于初始化问题,我正在将 redux 应用程序从 rc-form 迁移到 redux-form 包。我很确定 Redux-form 不会节省我的时间,但我希望应用程序会更稳定。感谢您的帮助!
    • 那行得通。但是发送initialValuei.edefaultChecked={true}怎么样。我希望它可以工作,但它不是
    • @Mbanda 您没有意识到“发送初始值”与设置“defaultChecked”是一个非常不同的问题(这很糟糕,但这是可悲的现实)。前者很容易,后者很棘手,因此更难。仅在评论中涵盖绝对是不够的,您应该将其作为单独的问题发布。
    猜你喜欢
    • 2017-12-27
    • 2016-11-05
    • 1970-01-01
    • 2022-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    相关资源
    最近更新 更多