如何在父类组件中获取子类组件的DOM ref [英] How to get the DOM ref of a child class component in a parent class component

查看:113
本文介绍了如何在父类组件中获取子类组件的DOM ref的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Parent.js:

import Child from './Child';类父扩展组件{构造函数(道具){超级(道具);this.refOfTheParent = React.createRef();}componentDidMount() {const parentDOM = this.refOfTheParent.current;//const childDOM = ???;}使成为() {返回 (<div ref={this.refOfTheParent}><孩子/>

);}}导出默认父级;

Child.js:

class Child extends Component {使成为() {返回 (<div>子组件</div>);}}导出默认子项;

有人可以帮我完成这段代码,其中 Parent::componentDidMount() 中的 childDOM 具有 的 DOM ref代码>.

奖励:如果 Parent 和 Child 都通过 react-redux connect 连接起来会怎么样.

解决方案

您可以使用 forwardRef

class Child 扩展 React.Component{使成为() {返回 (<div ref={this.props.forwardRef}>子组件

)}}导出默认 React.forwardRef((props, ref) => <Child {...props} forwardRef={ref}/>)

然后在父级

构造函数(道具){//...this.childRef = React.createRef();}使成为() {返回 (<div><子引用={this.childRef}/>

)}

更多信息这里

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.

解决方案

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

这篇关于如何在父类组件中获取子类组件的DOM ref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆