How to get refs from another component in React JS

前端 未结 4 579
时光取名叫无心
时光取名叫无心 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 15:58

    If your component are related (parent and child ) you can assign ref to child and can use it in parent

    If not then getElementById will come to rescue, but while selecting it please assign html type ex.

    const info = (document.getElementById("info") as HTMLDivElement)
    
    0 讨论(0)
  • 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:

    <section ref={sectionElement => this.sectionElement = sectionElement}>
        <Info/>
    </section>
    

    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 (
                <div className="homeMain">
                    <section ref={infoSection => this.infoSection = infoSection}>
                        <Info/>
                    </section>
    
                    <section ref={contactSection => this.contactSection = contactSection}>
                        <Contact />
                    </section>
                </div>
            );
        }
    }
    

    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:

    <HomePage ref={homePage => this.homePage = homePage} ... />
    <Header sections={[this.homePage.infoSection, this.homePage.contactSection]} ... />
    

    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"]
    });
    
    0 讨论(0)
  • 2021-02-12 16:19

    The React's main idea is passing props downward from parent to children (even to deeper levels of children - grandchildren I mean)

    Therefore, when we want the parent to do something which is triggered from (or belongs to) the children, we can create a callback function in the parent, then pass it down to children as props

    For your preference, this is a demonstration on how to pass callback functions downward through many levels of children and how to trigger them:

    Force React container to refresh data

    Re-initializing class on redirect

    In your case, you can access refs from children components as follows: (using string for ref - as you stated)

    Parent Component:

    import React, { Component } from 'react';
    // import Child component here
    
    export default class Parent extends Component {
      constructor(props){
        super(props);
        // ...
        this.getRefsFromChild = this.getRefsFromChild.bind(this);
      }    
    
      getRefsFromChild(childRefs) {
        // you can get your requested value here, you can either use state/props/ or whatever you like based on your need case by case
        this.setState({
          myRequestedRefs: childRefs
        });
        console.log(this.state.myRequestedRefs); // this should have *info*, *contact* as keys
      }    
    
      render() {
        return (
          <Child passRefUpward={this.getRefsFromChild} />
        )
      }  
    }
    

    Child Component:

    import React, { Component } from 'react';
    
    export default class Child extends Component {
      constructor(props){
        super(props);
        // ...
      }    
    
      componentDidMount() {
        // pass the requested ref here
        this.props.passRefUpward(this.refs);
    
      }    
    
      render() {
        return (
          <div className="homeMain">
            <section ref="info"> <Info/> </section>
    
            <section ref="contact"> <Contact /> </section>
          </div>          
        )
      }  
    }  
    
    0 讨论(0)
  • 2021-02-12 16:24

    ref is property of each this.props.children hence you can access ref of child component in parent via ref property on this.props.children

    Make sure you access ref after componentDidMount

    Edit :

    Try below set of code if this works :

    var myChild= React.Children.only(this.props.children);
    var clone = React.cloneElement(myChild, { ref: "myRef" });
    
    0 讨论(0)
提交回复
热议问题