ReactJs:如何获取引用来自其父项的组件的引用

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

如本 issue 中所建议,如果我想引用子组件,建议使用 refs。

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

我想要的是访问 Field 组件内给 input 的引用。那我们该怎么做呢?

我试过使用

  1. this.props.inputRef

  2. this.inputRef

但是 none 有效。请在这方面指导我。

将另一个 ref 分配给输入组件,将一个 ref 分配给 Field 组件。然后您可以访问子输入,例如 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>
    )
  }
}

但是您不需要在 componentDidMount 函数的两个地方都这样做。如果您没有任何其他逻辑,那么您可以在父项或子项中使用焦点命令

您可以传递一个将 refs 存储在父组件中的函数作为 prop。我已经通过示例为您制作了 fiddle

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