猿问

无法从其父 React JS 获取子组件引用对象

我想从子级向父级引用一个<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 等;但是来自 Parent 组件,因为我无法从 ChildComponent componentDidMount 计算它,因为这些组件尚未呈现。


这是我当前从浏览器控制台获得的结果:

如您所见,它current object向我显示了一个null值,但在里面您可以看到我想要获得的所有属性。



牧羊人nacy
浏览 144回答 1
1回答

aluckdog

因为您想获取这些标签的属性,例如 getBoundingClientRect()。我提供了使用 ref 调用 getBoundingClientRect() 的示例,并将字符串设置为 span 的 innerText。请检查一下。父组件示例import React from "react";import ChildComponentExample from "./ChildComponentExample";export default class ParentComponentExample extends React.Component {&nbsp; &nbsp; childRef = React.createRef();&nbsp; &nbsp; componentDidMount() {&nbsp; &nbsp; &nbsp; &nbsp; const childRef1 = this.childRef.current.innerRef1;&nbsp; &nbsp; &nbsp; &nbsp; const childRef2 = this.childRef.current.innerRef2;&nbsp; &nbsp; &nbsp; &nbsp; console.log(childRef2, 'childRef2');&nbsp; &nbsp; &nbsp; &nbsp; childRef2.current.innerText = 'This is SPAN';&nbsp; &nbsp; &nbsp; &nbsp; const rect = childRef1.current.getBoundingClientRect();&nbsp; &nbsp; &nbsp; &nbsp; console.log(rect, 'rect');&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ChildComponentExample ref={this.childRef}/>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }}子组件示例import React from "react";export default class ChildComponentExample extends React.Component {&nbsp; &nbsp; innerRef1 = React.createRef();&nbsp; &nbsp; innerRef2 = React.createRef();&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div ref={this.innerRef1}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span ref={this.innerRef2}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答