javascript - React 获取组件的高度
问题描述
我需要知道一个React 组件在另一个 React 组件中的高度。我知道可以通过调用来达到元素的高度this.cmref.current.clientHeight
。我正在寻找这样的东西:
子组件:
const Comp = () =>{
return(
<div>some other stuff here</div>
)
}
export default Comp
父组件:
class App extends React.Component{
constructor(props){
super(props);
this.compref = React.createRef();
}
componentDidSomething(){
const height = this.compref.current.clientHeight;
//which will be undefined
}
render(){
return(
<div>
<Comp ref={this.compref} />
</div>
)
}
}
这可能吗?提前致谢。
解决方案
您需要实际引用子组件的 div 以获得所需的元素,而不是子组件本身。为此,您可以将一个函数传递给孩子,然后孩子将其传递给 div。下面的工作示例:
const Comp = (props) =>{
return(
<div ref={props.onRef}>some other stuff here</div>
)
}
class App extends React.Component{
constructor(props){
super(props);
this.compref = React.createRef();
}
componentDidMount(){
const height = this.compref.current.clientHeight;
//which will be undefined --- No more!
console.log('height: ', height);
}
onCompRef = (ref) => {
this.compref.current = ref;
}
render(){
return(
<div>
<Comp onRef={this.onCompRef} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id='root' style='width: 100%; height: 100%'>
</div>
推荐阅读
- algorithm - 如何将一个值限制在一个范围内?
- android - ConstraintLayout 中的 ImageButton 缩放问题
- android - 如何以这种方式在日志中打印文本 R.string.text
- css - Align boostrap div at the end
- python - 如何在 n 秒后打印一些东西?
- java - Spring MongoDb BasicQuery equivalent for Aggregations
- c# - c#听键盘组合
- sql - Oracle中的子字符串和字符串计算
- java - 如果 Spinner getSelecteditem 如何更改 TextView 内容
- java - 递归存储的二叉搜索树问题