React - 更改输入时自动提交表单

React - automatic submission of form upon changing input

我正在尝试使用 onChange 事件在 React 中自动提交表单。它适用于常规 input 字段,但不知何故不适用于我的 React 组件的 react-select. Here's a gist

我专门尝试更新 startDateendDate 属性。我也收到此警告:EducationForm is changing an uncontrolled input of type text to be controlled。我怀疑这是因为 startDateendDate 没有初始值,所以我在构造函数中添加了这个:

this.state.attributes.startDate = ''
this.state.attributes.endDate = ''

但是,尽管如此,我仍然收到相同的警告。这是我尝试使用 Select 标签的 onChange 事件提交表单:

<Select
  className='form-control'
  name='startDate'
  value={attributes.startDate}
  required={true}
  onChange={e => {
    this.updateAttribute(e, 'startDate')
  }}
  options={this.options}
/>

<Select
  className='form-control'
  name='endDate'
  value={attributes.endDate}
  required={true}
  onChange={e => {
    this.updateAttribute(e, 'endDate')
  }}
  options={this.options}
/>

updateAttribute调用submitForm方法:

updateAttribute = (e: ReactEvent, attribute: string) => {
  e.preventDefault && e.preventDefault()

  const attributes = {
    ...this.state.attributes,
    [attribute]: e.target ? e.target.value : e
  }
  this.setState({ attributes: attributes }, () => this.submitForm())
}

您的问题出在您的 onChange 处理程序中。 React-Select 对 onChange

有一个非常具体的签名
function (
  One of <
    Object,
    Array<Object>,
    null,
    undefined
  >,
  {
    action required One of <
      "select-option",
      "deselect-option",
      "remove-value",
      "pop-value",
      "set-value",
      "clear",
      "create-option"
    >
  }
  ) => undefined

是的,大多数人对此感到困惑。你的 onChange 属性会变成这样:

onChange={(value, {action}) => this.updateValue(value, action)}

您的 updateValue 方法然后根据所采取的操作类型对您的 select 的值更改进行操作。单个 select 中的 React-Select 将为您提供 selected optionvalue 对象(构成 [=17= 的整个对象) ]).一个 React-Select in multi select 会给你一个对象数组作为 value。你的value类型不一样,要看是单还是多select,拍的action

此时,您如何处理 value 由您决定。使用那个 value,将适当的键应用于您正在发布的数据对象,然后调用您想要保存数据的任何方法。