How to get refs from another component in React JS

前端 未结 4 642
时光取名叫无心
时光取名叫无心 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: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 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 (
          
    ) } }

提交回复
热议问题