反应-专注于DOM中的“输入”元素(呈现为列表的元素),按键后消失

时间:2019-04-05 07:13:01

标签: javascript reactjs dom focus

我希望按键后保持对“输入”元素的关注

代码:

import React, { Component } from 'react'

class App extends Component {
  render() {
    return (
      <NewContactBox/>
    )
  }
}
class NewContactBox extends Component {
  constructor(props) {
    super(props)
    this.state = {
      name: '',
      email: '',
      phone: '',
    }
    this.fieldRefs = {
      name: React.createRef(),
      email: React.createRef(),
      phone: React.createRef(),
    }
  }
  hc = (ev, type, ref) => {
    this.setState({
      [type]: ev.target.value
    })
    // console.log(ref)
    ref.focus()
  }
  render() {
    const ContactInput = ({fields}) => (
      fields.map((f) => (
        <input
          key={f.id}
          className={`p-1 my-3 w-100 mr-3 ${f.id}`}
          size="16px"
          placeholder={f.placeholder}
          value={this.state[f.id]}
          ref={this.fieldRefs[f.id]}
          onChange={(e) => this.hc(e, f.id, this.fieldRefs[f.id].current)}
        />
      ))
    )
    return (
      <ContactInput
        fields={[
          { placeholder: "Name", id: 'name' },
          { placeholder: "Phone number", id: 'phone' },
          { placeholder: "Email", id: 'email' },
        ]}
      />
    )
  }
}

export default App

我尝试过

  1. Change01-以另一种方式在Input标记内声明引用

  2. Change02-不将引用显式传递给onChange,然后直接从this.fieldrefs

  3. 访问该引用
constructor(props) {
  this.fieldRefs = {} // Change01
}
hc = (ev, type) => { //Change02
  this.setState({
    [type]: ev.target.value
  })
  // console.log(this.fieldRefs[type].current)
  this.fieldRefs[type].current.focus()
}
...
      <input
        ...
        ref={(el) => this.fieldRefs[f.id] = el} //Change01
        onChange={(e) => this.hc(e, f.id)} //Change02
      />

但这没有帮助,每次按键后,body元素变为活动元素。

1 个答案:

答案 0 :(得分:0)

也许您需要将ContactInput声明移到render()之外,否则每次重新发布时都会重新创建一个新组件。例如,

  render() {
    return (
      <this.ContactInput
        fields={[
          { placeholder: "Name", id: 'name' },
          { placeholder: "Phone number", id: 'phone' },
          { placeholder: "Email", id: 'email' },
        ]}
      />
    )
  }

  ContactInput = ({fields}) => (
    // If react complains about returning multiple component, add this React.Fragment short syntax
    <React.Fragment>
      {fields.map((f) => (
        <input
          key={f.id}
          className={`p-1 my-3 w-100 mr-3 ${f.id}`}
          size="16px"
          placeholder={f.placeholder}
          value={this.state[f.id]}
          ref={this.fieldRefs[f.id]}
          onChange={(e) => this.hc(e, f.id, this.fieldRefs[f.id].current)}
        />
      ))}
    <React.Fragment/> 
  )