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

时间:2017-06-15 10:01:22

标签: javascript reactjs ref

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.

2 个答案:

答案 0 :(得分:3)

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>
    )
  }
}

答案 1 :(得分:0)

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