javascript - 如何从 React JS 中的另一个组件获取引用

标签 javascript reactjs

主App组件代码如下:

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

  render() {

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

使用 {this.props.children} 呈现的组件之一是主页,其中包含带有 refs 的部分。

主页的代码如下:

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

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

我怎样才能在 App 组件中获取这些引用,以便能够将它们作为 props 传递给 header ?

我试图在 App 组件的 componentDidMount 中执行它,但是 console.log(this.refs) 是空的。

有什么建议吗?

编辑

整个 App 组件:

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

最佳答案

React 的主要思想是将 props 从 parent 向下传递给 child (甚至传递给更深层次的 child ——我的意思是孙子)

因此,当我们想让父类做一些由子类触发(或属于)的事情时,我们可以在父类中创建一个回调函数,然后将其作为 Prop 传递给子类

根据您的喜好,这是一个关于如何通过多级子级向下传递回调函数以及如何触发它们的演示:

Force React container to refresh data

Re-initializing class on redirect

在您的情况下,您可以按如下方式从子组件访问引用:(使用字符串作为引用 - 如您所述)

父组件:

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

子组件:

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

关于javascript - 如何从 React JS 中的另一个组件获取引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40080742/

相关文章:

python - Django 静态文件 404(未找到)

javascript - 带有 Webpack 的内联 CSS,没有 HtmlWebpackInlineSourcePlugin?

javascript - CryptoJS.enc.Base64.stringify() 和普通 Base64 加密的区别

javascript - 使用 Node.js 和 mongodb 处理超时

javascript - 用 Jest 和 enzyme 进行测试。监视 react 组件的方法

Javascript 映射函数 - 将单词项传递给函数以返回 html 元素

javascript - 在 Javascript 中从 JSON 创建一个数组

javascript - 如何在我的代码中添加 if..else 语句

javascript - 如何判断混合数组是否包含字符串元素?

javascript - ReactJS 游戏 - 在组件之间切换 - 无法执行