React.js - input losing focus when rerendering

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

    For me, this was being caused by the search input box being rendered in the same component (called UserList) as the list of search results. So whenever the search results changed, the whole UserList component rerendered, including the input box.

    My solution was to create a whole new component called UserListSearch which is separate from UserList. I did not need to set keys on the input fields in UserListSearch for this to work. The render function of my UsersContainer now looks like this:

    class UserContainer extends React.Component {
      render() {
        return (
          
    (
    )} />
    ) } }

    Hopefully this helps someone too.

提交回复
热议问题