Не удается получить объект ref дочернего компонента из родительского объекта React JS - PullRequest
1 голос
/ 29 апреля 2020

Я хочу сослаться на <div> и <span> компонент от дочернего элемента к родителю.
Так что я кодирую что-то вроде:

class Parent extends Component {
    childRef = React.createRef()

    componentDidMount(){
      const childRef1 = this.childRef.current.innerRef1
      const childRef2 = this.childRef.current.innerRef2

      //... compute with the references childRef1 and childRef2
  }

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

Внутри дочернего элемента я получил что-то вроде:

 class ChildComponent extends Component {
    innerRef1 = React.createRef()
    innerRef2 = React.createRef()


  render(){
    return(
      <div ref={this.innerRef1}>
         <span ref={this.innerRef2}></span>
      </div>
    )
  }
}

Я хочу получить свойства этих тегов. Такие вещи, как getBoundingClientRect (), scrollTop и т. Д .; но из родительского компонента, потому что я не могу вычислить его из ChildComponent componentDidMount, потому что эти компоненты еще не отрисованы.

Это мой текущий результат из консоли браузера: enter image description here

Как видите, current object показывает мне значение null, но внутри вы можете видеть все свойства, которые я хочу получить.

1 Ответ

1 голос
/ 30 апреля 2020

Поскольку вы хотите получить свойства таких тегов, как getBoundingClientRect (). Я привел пример, где я вызвал getBoundingClientRect (), используя ref, а также я установил строку в innerText of span. Пожалуйста, проверьте его.

Пример родительского компонента

import React from "react";
import ChildComponentExample from "./ChildComponentExample";

export default class ParentComponentExample extends React.Component {
    childRef = React.createRef();

    componentDidMount() {
        const childRef1 = this.childRef.current.innerRef1;
        const childRef2 = this.childRef.current.innerRef2;

        console.log(childRef2, 'childRef2');
        childRef2.current.innerText = 'This is SPAN';
        const rect = childRef1.current.getBoundingClientRect();
        console.log(rect, 'rect');
    }

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

Пример дочернего компонента

import React from "react";

export default class ChildComponentExample extends React.Component {
    innerRef1 = React.createRef();
    innerRef2 = React.createRef();

    render() {
        return (
            <div ref={this.innerRef1}>
                <span ref={this.innerRef2}/>
            </div>
        )
    }
}
...