React.js - input losing focus when rerendering

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

    I got the same behavior.

    The problem in my code was that i created a nested Array of jsx elements like this:

    const example = [
                [
                    <input value={'Test 1'}/>,
                    <div>Test 2</div>,
                    <div>Test 3</div>,
                ]
            ]
    
    ...
    
    render = () => {
        return <div>{ example }</div>
    }
    

    Every element in this nested Array re-renders each time I updated the parent element. And so the inputs lose there "ref" prop every time

    I fixed the Problem with transform the inner array to a react component (a function with a render function)

    const example = [
                <myComponentArray />
            ]
    
     ...
    
    render = () => {
        return <div>{ example }</div>
    }
    

    EDIT:

    The same issue appears when i build a nested React.Fragment

    const SomeComponent = (props) => (
        <React.Fragment>
            <label ... />
            <input ... />
        </React.Fragment>
    );
    
    const ParentComponent = (props) => (
        <React.Fragment>
            <SomeComponent ... />
            <div />
        </React.Fragment>
    );
    
    0 讨论(0)
提交回复
热议问题