How to deal with a ref within a loop?

前端 未结 4 1531
北恋
北恋 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 23:04

    I discovered another way of tackling this:

    let dataCount = 0;
    
    class TestRef extends React.Component {
      state = {
        data: [
          {
            name: "abc"
          },
          { name: "def" }
        ]
      };
      focusInput = (thisHello) => this[`ref${thisHello}`].current.focus();
      render() {
        return (
          
    {this.state.data.map(o => { dataCount++ return { this[`ref${dataCount}`] = el; }} />; })}
    ); } }

    The dataCount is unnecessary if your Hello element has a key or unique ID to use as a variable.

提交回复
热议问题