使用 React / Redux Forms 覆盖 onChange 行为

Overriding onChange behavior with React / Redux Forms

我正在用 React 构建一个复杂的表单,并尝试使用 Redux Forms 作为辅助工具。

项目的要求是:

  1. 页面上的值会根据 输入字段(如 excel 电子表格)

  2. 至少会有一个字段同时作为输入 字段和一个依赖字段(它可以改变,但也可以改变 当其他字段更改时)

  3. 我想控制状态何时改变。默认情况下,它将 当输入改变时立即发生,但我宁愿延迟 像 this example.

第一个功能基本上是按照Redux Forms的教程来的,我已经搞定了。但是,其他两个需要修改字段更新时发生的情况,而我无法弄清楚如何做到这一点。我可以想象如何从头开始做这件事,但想看看是否有办法使用这个库来简化事情。

我的代码在 GitHub (side question, does anyone have insight why my GitHub pages site 上给出了 404?

您必须创建一个自定义组件以放置在 redux-form 的 Field 中,您在其中保存内部状态,并在需要时将其与 formReducer 同步。

您可以通过几个步骤实现此目的:

  1. 创建要在 Field 内部使用的自定义组件。这个组件注入with a meta and input prop.

  2. 为您的 React 组件创建 state,您将在其中跟踪最终发送到 formReducer 的数据。

  3. 在您的构造函数中,使用 props.input.value 设置您的初始状态。如果这样做,您可以将 'initialValues' 对象用于 reduxForm.

  4. 使用 react-reduxconnect 可以使用 react-form 的动作创建器。在您的情况下,您将使用 change action creator.

  5. 使用输入字段创建渲染函数并触发 change 操作以修改此字段的 formReducer 值。

所以这归结为这样的事情:

<Field
  name="daysPerWeek"
  component={MyCustomComponent} // 1
/>

...

class MyCustomComponent {
  constructor(props) {
    super(props);

    this.state = {
      value: props.input.value, // 2 and 3
    }
  }

  ....
}

4:

import { connect } from 'react-redux';
import { change } from 'react-form';

const mapDispatchToProps = (dispatch, ownProps) => ({
  ourCustomChange: (value) => dispatch(change(ownProps.meta.form, ownProps.input.name, value))
})

export default connect(undefined, mapDispatchToProps)(MyCustomComponent);

5:

....
 componentDidUpdate(prevProps, prevState) {
   if (prevState.value !== this.state.value) {
     this.debounceAndEmit();
   }
 }

 debounceAndEmit() {
   // Debounce for some time. Maybe use:
   // import { debounce } from 'throttle-debounce';
   // for that:
   debounce(2000, () => {
     this.props.ourCustomChange(this.state.value)
   })
 }

 handleChange(event) {
   // Do things here like trimming the string, regex, whatever.
   this.setState({ value: event.target.value })
 }

  render() {
    return (
      <input
        {...this.props.input} // Includes standard redux-form bindings for input fields. 
        value={this.state.value}
        onChange={this.handleChange.bind(this)}
      />
    )
  }
....

在某些情况下,您可能还必须使用 blur action creator。例如,当您在输入字段外单击时正在做一些事情。

如果您希望表单字段根据其他字段而改变,您应该使用 selectors 将它们的值注入到您的自定义组件中以对此做出响应。

这是否回答了您的问题?