reduxform - 如何使用单个 handleChange 函数处理单选按钮上的更改

reduxform - how to handle change on a radio button using a single handleChange function

我在我的 Laravel 项目(实施 React 15.4.2)中使用 redux-form,我的表单包含几个单选按钮。我需要一个 handleChange 函数来让它们记住检查的内容(如果它们从以前的值更改或第一次选择)但我不想为每个收音机写一个单独的按钮,或实施大量 if else 规则集来处理每个规则。

这是我的字段之一(只是 'yes' 值):

<input type="radio" onChange={this.handleChange.bind(this, 'maintain_licence', 'yes')} checked={maintain_licence.value === 'yes'} id="maintain-licence-yes" value="yes" name="maintain_licence" /><span>Yes</span>

这就是我对单个单选按钮的更改,基于正在与之交互的名为 maintain_licence 的单选按钮:

handleChange(fieldName, value) {
    if(fieldName === 'maintain_licence') {
        this.props.fields.maintain_licence.onChange(value);
    }
}

这很好用 - 但是,由于我的表单中有大约 20 个收音机,我可以想象这个函数会变得相当长。理想情况下,我想要类似于:

handleChange(fieldName, value) {
   this.props.fields.fieldName.onChange(value);
}

但是当它试图找到一个实际名为 'fieldName' 的字段时,它会抛出一个错误,指出它不能 运行 onChange 一个未定义的值。

基本上我只需要找到一种方法来使用单个函数来处理所有单选按钮上的更改,但我不知道该怎么做。

您可以使用 属性 访问器来获得您想要的 属性。类似于:

handleChange(fieldName, value) {
    this.props.fields[fieldName].onChange(value);
}

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors