In React ES6, why does the input field lose focus after typing a character?

前端 未结 10 2100
悲&欢浪女
悲&欢浪女 2020-12-08 12:54

In my component below, the input field loses focus after typing a character. While using Chrome\'s Inspector, it looks like the whole form is being re-rendered instead of ju

相关标签:
10条回答
  • 2020-12-08 13:42

    set the correct id, make sure no other component has same id, set it unique, and it should not change on state update, most common mistake is updating the id with changed value on state update

    0 讨论(0)
  • 2020-12-08 13:45

    Your form is rerendered when you type in a character, because you have an onChange method, which changes the state. Every state change causes the form to rerender and that is why the input method is loosing focus.

    Since you are using redux, the best way would be to store the post title value in the redux object. Also, you may want to have a look at using redux-form for your form.

    To get the value of the input without the re-rendering you need to use refs.

    0 讨论(0)
  • 2020-12-08 13:48

    What's happening is this:

    When your onChange event fires, the callback calls setState with the new title value, which gets passed to your text field as a prop. At that point, React renders a new component, which is why you lose focus.

    My first suggestion would be to provide your components keys, particularly the form and the input itself. Keys allow React to retain the identity of components through renders.

    Edit:

    See this documentation on keys: https://reactjs.org/docs/lists-and-keys.html#keys

    0 讨论(0)
  • 2020-12-08 13:50

    This happened to me although I had keys set!

    Here's why:

    I was using a key from a text field. Inside the same block; I had an input field to update the value of the same text field. Now, since component keys are changing, react re-renders the UI. Hence loosing focus.

    What to take from this:

    Don't use keys which are constantly changing.

    0 讨论(0)
提交回复
热议问题