React.js - input losing focus when rerendering

后端 未结 19 2070
猫巷女王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:13

    I keep coming back here again and again and always find the solution to my elsewhere at the end. So, I'll document it here because I know I will forget this again!

    The reason input was losing focus in my case was due to the fact that I was re-rendering the input on state change.

    Buggy Code:

    import React from 'react';
    import styled from 'styled-components';
    
    class SuperAwesomeComp extends React.Component {
      state = {
        email: ''
      };
      updateEmail = e => {
        e.preventDefault();
        this.setState({ email: e.target.value });
      };
      render() {
        const Container = styled.div``;
        const Input = styled.input``;
        return (
          
            
          
        )
      }
    }
    

    So, the problem is that I always start coding everything at one place to quickly test and later break it all into separate modules. But, here this strategy backfires because updating the state on input change triggers render function and the focus is lost.

    Fix is simple, do the modularization from the beginning, in other words, "Move the Input component out of render function"

    Fixed Code

    import React from 'react';
    import styled from 'styled-components';
    
    const Container = styled.div``;
    const Input = styled.input``;
    
    class SuperAwesomeComp extends React.Component {
      state = {
        email: ''
      };
      updateEmail = e => {
        e.preventDefault();
        this.setState({ email: e.target.value });
      };
      render() {
        return (
          
            
          
        )
      }
    }
    

    Ref. to the solution: https://github.com/styled-components/styled-components/issues/540#issuecomment-283664947

提交回复
热议问题