How to deal with a ref within a loop?

前端 未结 4 1552
北恋
北恋 2021-02-12 22:13

Below is my parent component with multiple inputs from a loop. How can I choose one input to focus? Do I have to create a dynamic ref in this case?

4条回答
  •  心在旅途
    2021-02-12 22:50

    Using a general useFocus hook

    // General Focus Hook
    const useFocus = (initialFocus = false, id = "") => {
        const [focus, setFocus] = useState(initialFocus)
        return ([
            (newVal=true) => setFocus(newVal), {
                autoFocus: focus,
                key: `${id}${focus}`,
                onFocus: () => setFocus(true),
                onBlur: () => setFocus(false),
            },
        ])
    }
    
    const data: [{
            name: "abc"
        },{ 
            name: "def" 
    }]
    
    const TestRef = () => {
    
        const focusHelper = data.map( (_,i) => {
            const [setFocus, focusProps]= useFocus(false, i)
            return {setFocus, focusProps}
        }) 
    
        return (
          
    {data.map( (o,i) => ( ; ))}
    ); }

    You can find more info here: Set focus on input after render

提交回复
热议问题