[英]Can't get Child Component ref object from their parent 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
值,但在里面您可以看到我想要获得的所有属性。
因为您想获取这些标签的属性,例如 getBoundingClientRect()。 我提供了使用 ref 调用 getBoundingClientRect() 的示例,并将字符串设置为 span 的 innerText。 请检查一下。
父组件示例
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>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.