1 回答

TA貢獻1829條經(jīng)驗 獲得超4個贊
因為您想獲取這些標簽的屬性,例如 getBoundingClientRect()。我提供了使用 ref 調(diào)用 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>
)
}
}
添加回答
舉報