React.js - input losing focus when rerendering

后端 未结 19 2078
猫巷女王i
猫巷女王i 2020-12-05 01:49

I am just writing to text input and in onChange event i call setState, so React rerenders my UI. The problem is that the text input always lose a f

19条回答
  •  余生分开走
    2020-12-05 02:16

    If the input field is inside another element (i.e., a container element like

    ...
    -- the ellipses here indicating omitted code), there must be a unique and constant key on the container element (as well as on the input field). Elsewise, React renders up a brand new container element when child's state is updated rather than merely re-rendering the old container. Logically, only the child element should be updated, but...

    I had this problem while trying to write a component that took a bunch of address information. The working code looks like this

    // import react, components
    import React, { Component } from 'react'
    
    // import various functions
    import uuid from "uuid";
    
    // import styles
    import "../styles/signUp.css";
    
    export default class Address extends Component {
      constructor(props) {
        super(props);
        this.state = {
          address1: "",
          address2: "",
          address1Key: uuid.v4(),
          address2Key: uuid.v4(),
          address1HolderKey: uuid.v4(),
          address2HolderKey: uuid.v4(),
          // omitting state information for additional address fields for brevity
        };
        this.handleChange = this.handleChange.bind(this);
      }
    
      handleChange(event) {
        event.preventDefault();
        this.setState({ [`${event.target.id}`]: event.target.value })
      }
    
      render() {
        return (
          
    {/* omitting rest of address fields for brevity */}
    ) } }

    Sharp-eyed readers will note that

    is a containing element, yet it doesn't require a key. The same holds for <> and or even
    Why? Maybe only the immediate container needs a key. I dunno. As math textbooks say, the explanation is left to the reader as an exercise.

提交回复
热议问题