如何获取父类组件中子类组件的DOM引用

时间:2018-12-19 09:48:54

标签: reactjs ref

我很难理解docs关于如何从父 class 组件访问子 class 组件的DOM ref的信息。 / p>

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;

有人可以帮我完成这段代码吗,其中childDOM中的Parent::componentDidMount()的DOM引用为<Child />

奖金:如果将父级和子级都通过react-redux connect连接起来,会怎样?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以在

子组件中的props中传递引用
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