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

标签 javascript reactjs ref

如本 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 的 ref。那么我们该怎么做呢?

我试过用

  1. this.props.inputRef

  2. this.inputRef

但没有一个有效。请在这方面指导我。

最佳答案

您可以传递一个将 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>
    )
  }
}

关于javascript - ReactJs:如何获取引用来自其父项的组件的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44564565/

相关文章:

javascript - 堆积条形图未正确更新 d3js

javascript - 将 Highcharts 集成到 Angular-gridster

css - React中的Bootstrap 4 Scrollspy无法正常工作

reactjs - Ant 设计日历 : How to Change the Day of Week Format

javascript - React 组件状态问题与重复组件

reactjs - React-createRef() Api-this.child.current 为 null

c# - 在方法中创建结构时,引用返回不起作用

javascript - jQuery:$.ajaxSetup(beforeSend) 和 $(document).ajaxSend 之间有什么区别吗?

php - 如何使用 gmail 上下文小工具访问电子邮件附件

javascript - React 将 ref 传递给相邻组件