ReactJs: How to get ref of a component whose ref comes from its parent

[亡魂溺海] 提交于 2019-12-11 06:14:10

问题


As suggested in this issue, this is how refs are suggested to use in case I want to ref a child component.

findDOMNode(childComponentStringRef)

class Field extends Component {
  componentDidMount() {
    // this.inputNode.focus(); // Basically I want to access the ref to input here as well
  }

  render() {
    return (
      <input type='text' ref={this.props.inputRef} />
    )
  }
}

class MyComponent extends Component {
  componentDidMount() {
    this.inputNode.focus();
  }

  render() {
    return (
      <div>
        Hello, <Field inputRef={node => this.inputNode = node} />
      </div>
    )
  }
}

What I want is to access the ref, given to input inside the Field Component as well. So how can we do that?

I tried using

  1. this.props.inputRef

  2. this.inputRef

But none works. Please guide me on this one.


回答1:


Assign another ref to the input component and one to the Field component. then you can access the child input like this.inputNode.inputRef.focus();

class Field extends Component {
  componentDidMount() {
    this.inputRef.focus(); 
  }

  render() {
    return (
      <input type='text' ref={ip=> this.inputRef= node} />
    )
  }
}

class MyComponent extends Component {
  componentDidMount() {
    this.inputNode.inputRef.focus(); 

  }

  render() {
    return (
      <div>
        Hello, <Field ref={node => this.inputNode = node} />
      </div>
    )
  }
}

However you don;t need to do it at both places in the componentDidMount function. If you don;t have any other logic, then you can just have the focus command in either of the parent or child




回答2:


You can pass a function that stores refs in parent component as a prop. I've made a fiddle for you with an example.

class Field extends Component {
  componentDidMount() {
    this.props.setChildRef('inputRef', this.inputRef);
    this.inputRef.focus(); // Basically I want to access the ref to         input here as well
  }

  render() {
    return (
      <input type='text' ref={ip=> this.inputRef= ip} />
    )
  }
};


class MyComponent extends Component {
  componentDidMount() {
    this.inputRef.focus();
  }

  setChildRef = (name, ref) => {
    this[name] = ref;
  }

  render() {
    return (
      <div>
        Hello, <Field setChildRef={this.setChildRef} ref={node => this.inputNode = node} />
      </div>
    )
  }
}


来源:https://stackoverflow.com/questions/44564565/reactjs-how-to-get-ref-of-a-component-whose-ref-comes-from-its-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!