Redux-Form 在自定义组件中分离显示值和提交值

Redux-Form separating displayed value and submitted value in custom component

我有一个自定义组件 CurrencyBox,我使用 redux-form 来提交和验证表单。它非常适合输入“123,345”、“1.000.000”或“9.000,123”等输入。

今天,我需要将输入值 (1.000.000,456) 作为 (1000000,456) 发送到服务器。

简而言之,显示的值必须像 123.456,789 但提交的值必须是 123456,789

有办法处理吗?

我检查了标准化器等,但这些对我来说都不是可行的解决方案。我只想将显示值和提交值分开。

此致。

您需要为输入组件创建一个包装器组件,例如 TextField,该组件应该接收掩码和实际值,您需要为 onChange、[=13 设置一些处理程序=] 和您需要的任何其他回调,例如:

const { string, func } = PropTypes;

class TextField extends Component {
  static propTypes = {
    value: string,
    onChange: func,
    format: string,
  };

  getFormat(value) {
    // set the format that you need
    // based on the format prop or any other option
    return applyFormat(value);
  }

  handleChange = (event) => {
    const value = event.target.value;
    const { onChange } = this.props;

    if (onChange) {
      // Before returning the value
      // you need to remove the format
      onChange(removeFormat(value));
    }
  }

  render() {
    const { value } = this.props;

    return (
      <input
        type="text"
        value={this.getFormat(value)}
        onChange={this.handleChange}
      />
    );
  }
}

这是一个非常简单的示例,说明您可以做什么,基本上是在呈现您设置格式的值之前,在 onChange 上您需要删除格式,您可以实施 onBlur而不是 onChange,如果你使用 redux,数据将被发送到你的 reducer,直到用户完成编辑,防止在每次击键时调用 reducer。

用法:

<TextField
 value={this.props.dataFromRedux}
 onChange={this.props.actionCreatorToSaveValueOnState}
/>

希望对您有所帮助!