1 回答
TA贡献1847条经验 获得超7个赞
因为您想获取这些标签的属性,例如 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>
)
}
}
添加回答
举报