javascript - Redux-form onChange 处理程序可能被覆盖

标签 javascript reactjs redux-form

我创建了一个显示是和否单选按钮的条件字段。如果选择是,则应显示子组件。

下面的代码实现了这一点。问题是选择是或否未在 redux 状态中注册。如果我删除 onChange 函数,则 redux 状态将更新为 Yes 或 No 值,但子组件当然不会显示。

我相信我传递的 onChange 函数正在覆盖 redux-form 传递的其他一些 onChange 函数。尝试了很多东西,但结果相同。

我正在考虑将 value 属性与 ReactLink 链接起来,但它已被弃用。

使用 React 0.15、Redux-Form 6.0 alpha 和 ES7。

const YesNoRadioButtonGroup = (props) =>
  <RadioButtonGroup {...props}>
    <RadioButton value='Yes' label='Yes' className={s.radio}/>
    <RadioButton value='No' label='No' className={s.radio}/>
  </RadioButtonGroup>

// TODO: Clear child fields when "No" is selected
// TODO: See if we can generalize into ConditionalField
export class ConditionalRadio extends React.Component {

  state = {conditional: false}

  updateConditional(event) {
    console.log(event)
    this.setState({conditional: event.target.value === 'Yes'})
  }

  render() {
    return <div>
      <Field name={this.props.name}
             component={YesNoRadioButtonGroup}
             onChange={::this.updateConditional} />  // The trouble line.

      {this.state.conditional ? this.props.children : null}
    </div>
  }
}    

它是这样使用的:

       <ConditionalRadio name='willRelocate'>
              <Field name='willRelocateTo.withinCurrentState' component={Checkbox} label='Within Current State'/>
              <Field name='willRelocateTo.outOfState' component={Checkbox} label='Out of State'/>
              <Field name='willRelocateTo.outOfCountry' component={Checkbox} label='Out of Country'/>
        </ConditionalRadio>

最佳答案

如果您在创建 redux-form 时定义了字段名称,那么您只需在自定义更改事件处理程序中为该字段调用默认的 onChange 事件。

在你的情况下应该是:

  updateConditional(event) {
    this.setState({conditional: event.target.value === 'Yes'});
    this.props.fields.name.onChange(event);
  }

关于javascript - Redux-form onChange 处理程序可能被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600218/

相关文章:

javascript - Redux-form,如何将Field名称设置为动态字符串?

javascript - 将 jQuery 'this' 与多个元素的选择器一起使用

javascript - 谷歌应用脚​​本: How to set return to my page?

reactjs - TypeError : this. props.data.map 不是一个函数

reactjs - Redux 表单禁用字段数组上的 Enter 按钮

javascript - 无法在文本字段中输入任何文本

javascript - 如何在 TypeScript 中实现 clone() 方法?

javascript - keyup 和 keydown 不同步?

reactjs - React - 如何以内联样式显示 HEX 颜色而不是 RGB?

ReactJS MaterialUI 复选框 - 在 onCheck() 中设置状态