How to get refs from another component in React JS

前端 未结 4 581
时光取名叫无心
时光取名叫无心 2021-02-12 15:44

The code in main App component is as follows :

class App extends Component {
  componentDidMount(){
      console.log(this.ref);
      debugger;
  }

  render()         


        
4条回答
  •  一向
    一向 (楼主)
    2021-02-12 16:15

    According to Refs to Components, string-based refs -- while not deprecated -- are superseded by the callback-based syntax, for example:

    this.sectionElement = sectionElement}>

    The string-based ref is likely to be deprecated soon, which also implies that this.refs is affected as well. As such, I would recommend you take these into consideration, and provide instance methods or properties to expose refs instead:

    class HomePage extends Component {
        render() {
            return (
                
    this.infoSection = infoSection}>
    this.contactSection = contactSection}>
    ); } }

    After that, you'll need to obtain a ref to HomePage as well, on which you can then access infoSection and contactSection as properties, which you can then pass as props to Header, for example:

     this.homePage = homePage} ... />
    

    Your exact application structure is unknown to me, but the general principle will work everywhere: expose refs through instance methods or properties, obtain a ref to the component exposing its refs, then access the inside refs through the exposed properties.


    Edit

    If you would keep using string-based refs for now instead, you could define a getter (although refs should be directly accessible as well):

    Object.defineProperty(this, "infoSection" {
        get: () => this.refs["infoSection"]
    });
    

提交回复
热议问题