代码之家  ›  专栏  ›  技术社区  ›  Bargain23

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

  •  4
  • Bargain23  · 技术社区  · 7 年前

    onChange 事件。它正常工作 input 但不知怎么的 react-select gist 我的反应成分。

    我特别想更新 startDate endDate EducationForm is changing an uncontrolled input of type text to be controlled . 我想是因为 实际结束 没有初始值,所以我在构造函数中添加了以下内容:

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

    一旦改变 事件 Select

    <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())
    }
    
    0 回复  |  直到 7 年前
        1
  •  0
  •   Steve -Cutter- Blades    6 年前

    你的问题在你的 onChange 处理程序。React Select有一个非常特殊的签名

    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={(value, {action}) => this.updateValue(value, action)}

    你的 updateValue value 所选对象的 option (构成这个的整个物体 ). 在multi Select中的React Select将给您一个对象数组作为 . 你的 价值 类型不同,这取决于它是单选还是多选 action

    你用你的 价值 现在由你决定。拿着那个 价值 ,将适当的键应用于要发布的数据对象,并调用要保存数据的任何方法。