从状态创建选择选项,除非单击,否则不会更新表单json

时间:2018-11-05 14:30:38

标签: javascript reactjs react-redux redux-form react-select

我有一个redux-formreact-select一起工作。 react-select可以通过在选择文本字段中输入内容来动态创建新的选择选项。

在我的示例中,您将看到我已经更新了视图,以便新创建的选项突出显示为选中状态并显示在选择字段中。

但是,这不会更新我的表单json,除非我单击新创建的选项,看起来好像它已经被选中。

要复制:在选择框中键入-您会注意到新创建的选项已突出显示,并且选择了已更新的字段。但是您还将看到json值保持不变。单击新创建的选项,您将看到值更改。

Codesandbox示例:https://codesandbox.io/s/k2v2922nq5

import React from "react";
import { Field, reduxForm, FieldArray } from "redux-form";
import TextField from "material-ui/TextField";
import { RadioButton, RadioButtonGroup } from "material-ui/RadioButton";
import Checkbox from "material-ui/Checkbox";
import SelectField from "material-ui/SelectField";
import MenuItem from "material-ui/MenuItem";
import asyncValidate from "./asyncValidate";
import validate from "./validate";
import CreatableSelect from "react-select/lib/Creatable";
const CustomStyle = {
  option: (base, state) => ({
    ...base,
    display: "inline",
    marginRight: "10px",
    backgroundColor: state.isSelected ? "#00285C" : "#eee",
    cursor: "pointer"
  }),
  menuList: () => ({
    padding: 10,
    display: "inline-flex"
  }),
  menu: () => ({
    position: "relative"
  })
};

const createOption = (label: string) => ({
  label,
  value: label.toLowerCase().replace(/\W/g, "")
});
class LastNameSelectInput extends React.Component {
  constructor(props) {
    super(props);
  }

  state = {
    value: this.props.options[0],
    options: this.props.options
  };
  handleCreate = (inputValue: any) => {
    this.setState({ isLoading: true });
    setTimeout(() => {
      const { options } = this.state;
      const newOption = createOption(inputValue);
      this.setState({
        isLoading: false,
        options: [...options, newOption],
        value: newOption
      });
    }, 1000);
  };
  render() {
    const { input, options } = this.props;
    return (
      <div>
        <style>
          {`.react-select__dropdown-indicator,.react-select__indicator-separator {
          display: none;
        }`}
        </style>
        <CreatableSelect
          classNamePrefix="react-select"
          options={this.state.options}
          menuIsOpen={true}
          onChange={value => {
            let newValue = input.onChange(value);
            this.setState({ value: newValue });
          }}
          onBlur={() => input.onBlur(input.value)}
          onCreateOption={this.handleCreate}
          value={this.state.value}
          styles={CustomStyle}
          isClearable
        />
      </div>
    );
  }
}

const MaterialUiForm = props => {
  const { handleSubmit, options, pristine, reset, submitting } = props;

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <Field name="firstName" component={LastNameSelectInput} {...props} />
      </div>
    </form>
  );
};

export default reduxForm({
  form: "MaterialUiForm", // a unique identifier for this form
  validate,
  asyncValidate
})(MaterialUiForm);

1 个答案:

答案 0 :(得分:1)

因此,当您创建一个新选项时,您将设置React组件状态,但不做任何事情来告知redux-form,它使用Redux存储作为其状态。这始终是造成混乱的主要原因(React组件状态与Redux存储)。

解决方案是让redux-form知道我们也要 选择 。这可以通过手动分配onChange来完成。

forked您的沙盒,并添加了手动发送。

重大更改(为简洁起见,省略了现有代码):

处理创建

// takes the input to fire dispatch upon
handleCreate = input => (inputValue: any) => {

...
this.setState(...);
input.onChange(newOption); // manually dispatching the change to let redux-form know

渲染

// pass a ref to the input in handleCreate
onCreateOption={this.handleCreate(input)}

redux-form让我们也使用字段名手动触发change,但是最好使用绑定的input