【问题标题】:How to get the DOM ref of a child class component in a parent class component如何在父类组件中获取子类组件的DOM ref
【发布时间】:2019-05-19 18:50:19
【问题描述】:

我很难理解 docs 关于如何从父 class 组件访问子 class 组件的 DOM 引用。

Parent.js:

import Child from './Child';

class Parent extends Component {
    constructor(props) {
        super(props);
        this.refOfTheParent = React.createRef();
    }

    componentDidMount() {
        const parentDOM = this.refOfTheParent.current;
        //const childDOM = ???;
    }

    render() {
        return (
            <div ref={this.refOfTheParent}>
                <Child />
            </div>
        );
    }
}

export default Parent;

Child.js:

class Child extends Component {

    render() {
        return (
            <div>Child component</div>
        );
    }
}

export default Child;

如果Parent::componentDidMount() 中的childDOM 的DOM 引用为&lt;Child /&gt;,请有人帮我完成这段代码。

奖励:如果 Parent 和 Child 都通过 react-redux connect 连接会是什么样子。

【问题讨论】:

  • 你想访问 div 或者你想从 parent 渲染一些值为什么我要问,因为使用 Refs 你应该使用 State,不推荐使用 refs
  • 我想要 Child 中的 div。与 parentDOM 相同,但用于 Child。
  • 这样做的目的是什么?可能是需要以另一种方式解决的 XY 问题。

标签: reactjs ref


【解决方案1】:

你可以使用forwardRef

class Child extend React.Component{
   render() {
      return (
        <div ref={this.props.forwardRef}> Child component </div>
      )
   }
}

export default React.forwardRef((props, ref) => <Child {...props} forwardRef={ref} />)

然后在父级中

constructor(props) {
  // ...
  this.childRef = React.createRef();
}

render() {
    return (
       <div>
         <Child ref={this.childRef} />
       </div>
    )
}

更多信息here

【讨论】:

  • 你能用 forwardRef 更新我的 Child.js 代码吗?我很傻
  • @horgen 没有看到你在谈论课程 :)
【解决方案2】:

你可以在子组件的 props 中传递 ref,比如

import React,{Component} from 'react';
import Child from './Child';
class Parent extends Component {
    constructor(props) {
        super(props);
        this.refOfTheParent = React.createRef();
        this.childRef=React.createRef();
    }

    componentDidMount() {
        const parentDOM = this.refOfTheParent.current;
         const childDom=this.childRef.current;
         console.log(childDom);
        //const childDOM = ???;
    }

    render() {
        return (
            <div ref={this.refOfTheParent}>
                <Child childRef={this.childRef}/>
            </div>
        );
    }
}
export default Parent

子组件

import React,{Component} from 'react';
class Child extends Component {
    render() {
        return (
            <div ref={this.props.childRef} id="1">Child component</div>
        );
    }
}

export default Child;

Demo

【讨论】:

  • 还没有尝试过,但是如果没有forwardRef,这不会返回类节点而不是Child的DOM节点吗?
  • 我没找到你
  • @horgen 这是一个很好的问题,如果你知道答案,请告诉我。如果确实像您预期的那样工作,那么下一个问题是为什么我们需要forwardRef :) 让我知道
猜你喜欢
  • 1970-01-01
  • 2022-12-13
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 1970-01-01
相关资源
最近更新 更多