How to get the DOM ref of a child class component in a parent class component

£可爱£侵袭症+ 提交于 2021-01-01 17:49:24

问题


I'm having a hard time understanding the docs on how to access the DOM ref of a child class component from the parent class component.

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;

Could someone please finish this code for me where childDOM in Parent::componentDidMount() has the DOM ref of <Child />.

Bonus: How would it look if Parent AND Child are both connected with react-redux connect.


回答1:


You can use 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} />)

Then in parent

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

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

more info here




回答2:


you can pass the ref in props in child component like

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

Child Component

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



来源:https://stackoverflow.com/questions/53848512/how-to-get-the-dom-ref-of-a-child-class-component-in-a-parent-class-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!