最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get refs from another component in React JS - Stack Overflow

programmeradmin3浏览0评论

The code in main App component is as follows :

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

  render() {

    return (
        <div>
            <Header/>
            {this.props.children}
            <Footer/>
        </div>
    );
  }
}

And one of the components which renders with {this.props.children} is HomePage, where are sections with refs.

The code of a HomePage is as follows :

render(){
     return (
        <div className="homeMain">
            <section ref="info"> <Info/> </section>

            <section ref="contact"> <Contact /> </section>
       </div>
    );
}

How can I get those refs inside App component to be able to pass them as props to header?

I'm trying to do it inside componentDidMount in App component, but console.log(this.refs) is empty.

Any advice?

EDIT

The whole App component :

import React, {Component} from 'react';
import Footer from './common/footer';
import Header from './common/header';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as actions from './components/homepage/login/authActions';

class App extends Component {
    componentDidMount(){
        console.log(this.props.children.refs);
        debugger;

    }

    render() {
        return (
            <div>
                <Header route={this.props.location.pathname}
                        language={this.props.language.labels}
                        authenticated={this.props.authenticated}
                        signoutAction={this.props.actions}
                        offsets={this.props.offsets}
                />
                {React.cloneElement(this.props.children, {
                    currentLanguage: this.props.language.labels,
                    authenticated: this.props.authenticated
                })}
                <div className="clearfix"/>
                <Footer currentLanguage={this.props.language.labels}/>
            </div>
        );
    }
}

function mapStateToProps(state, ownProps) {
    return {
        language: state.language,
        authenticated: state.auth.authenticated,
        offsets: state.offsets
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actions, dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

The code in main App component is as follows :

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

  render() {

    return (
        <div>
            <Header/>
            {this.props.children}
            <Footer/>
        </div>
    );
  }
}

And one of the components which renders with {this.props.children} is HomePage, where are sections with refs.

The code of a HomePage is as follows :

render(){
     return (
        <div className="homeMain">
            <section ref="info"> <Info/> </section>

            <section ref="contact"> <Contact /> </section>
       </div>
    );
}

How can I get those refs inside App component to be able to pass them as props to header?

I'm trying to do it inside componentDidMount in App component, but console.log(this.refs) is empty.

Any advice?

EDIT

The whole App component :

import React, {Component} from 'react';
import Footer from './common/footer';
import Header from './common/header';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as actions from './components/homepage/login/authActions';

class App extends Component {
    componentDidMount(){
        console.log(this.props.children.refs);
        debugger;

    }

    render() {
        return (
            <div>
                <Header route={this.props.location.pathname}
                        language={this.props.language.labels}
                        authenticated={this.props.authenticated}
                        signoutAction={this.props.actions}
                        offsets={this.props.offsets}
                />
                {React.cloneElement(this.props.children, {
                    currentLanguage: this.props.language.labels,
                    authenticated: this.props.authenticated
                })}
                <div className="clearfix"/>
                <Footer currentLanguage={this.props.language.labels}/>
            </div>
        );
    }
}

function mapStateToProps(state, ownProps) {
    return {
        language: state.language,
        authenticated: state.auth.authenticated,
        offsets: state.offsets
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actions, dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
Share Improve this question edited Oct 17, 2016 at 8:31 Boky asked Oct 17, 2016 at 7:31 BokyBoky 12.1k30 gold badges101 silver badges171 bronze badges 9
  • this.refs will show all the refs of current component and you have not defined any refs there. – Rajesh Commented Oct 17, 2016 at 7:33
  • But they are defined in one of the child components. How can I get them? – Boky Commented Oct 17, 2016 at 7:35
  • @Boky you mean pass refs from child to parent via props? upward? – KOTIOS Commented Oct 17, 2016 at 7:35
  • You can't and you should not. Can you tell us what exactly are you trying to achieve? – Rajesh Commented Oct 17, 2016 at 7:36
  • 1 If you want to do something like this i think that you should define a method on children component and call the method from parent via refs, another way could be the implementation of a event emitter – Salvatore Commented Oct 17, 2016 at 8:35
 |  Show 4 more comments

2 Answers 2

Reset to default 10

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

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)

  1. 暂无评论