Redux表格 - >自动对焦首次输入

时间:2018-05-15 21:20:31

标签: forms redux autofocus

我有Redux-Form组件,我需要一个自动聚焦

现在它还没有用。每次自动对焦首次输入时我该怎么办?

const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
  <div>
    <div className ="group">
      <input className="text"
      {...input}
      type={type}/>
      <label>{label}</label>
      <span className="highlight"></span>
      <span className="bar"></span>
      {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
    </div>
  </div>
)


  <Field name="name"
    type="text"
    component={renderField}
    label="Username"
    autoFocus
    require/>

  <Field name="email"
   type="email"
    component={renderField}
     label="Email"
    require/>

1 个答案:

答案 0 :(得分:1)

autoFocus未被放入input组。我们需要手动处理这个。

进入input的唯一关键是:

export type InputProps = {
  checked?: boolean,
  name: string,
  onBlur: { (eventOrValue: Event | any): void },
  onChange: { (eventOrValue: Event | any): void },
  onDrop: { (event: Event): void },
  onDragStart: { (event: Event): void },
  onFocus: { (event: Event): void },
  value: any
}

如源代码所示 - https://github.com/erikras/redux-form/blob/master/src/FieldProps.types.js.flow#L29-L38

另见文档 - https://redux-form.com/7.3.0/docs/api/field.md/#input-props

所以我们会修改我们的renderField以处理所有其他道具并将其传递给input,如下所示:

const renderField = ({ input, label, meta: { touched, error, warning }, custom, ...inputProps }) => (
  <div>
    <div className ="group">
      <input className="text" {...input} {...inputProps} />
      <label>{label}</label>
      <span className="highlight"></span>
      <span className="bar"></span>
      {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
    </div>
  </div>
)

注意更改,现在是<input className="text" {...input} {...inputProps} />

我已将custom添加到destructure中,以便将其删除,因为这是FieldProps - https://github.com/erikras/redux-form/blob/master/src/FieldProps.types.js.flow#L40-L63

中的内容