How to deal with a ref within a loop?

前端 未结 4 1532
北恋
北恋 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:00

    You can use callback refs to generate and store the dynamic ref of each input in an array. Now you can refer to them using the index of the ref:

    const Hello = React.forwardRef((props,  ref) => );
    
    class Button extends React.Component {
      onClick = () => this.props.onClick(this.props.id);
    
      render() {
        return (
          
        );
      }
    }
    
    class TestRef extends React.Component {
      state = {
        data: [
          {
            name: "abc"
          },
          { name: "def" }
        ]
      };
      
      inputRefs = [];
      
      setRef = (ref) => {
        this.inputRefs.push(ref);
      };
      
      focusInput = (id) => this.inputRefs[id].focus();
      
      render() {
        return (
          
    {this.state.data.map(({ name }) => ( ))}
    ); } } ReactDOM.render(, document.getElementById("root"));
    
    
    
    

提交回复
热议问题