Ama*_*ira 2 height components render reactjs
所以,大家好,基本上我正在使用react,我想通过props获取父div的高度,并使它的孩子具有相同的高度。每次调整窗口大小时,父div都会渲染。我尝试使用componentDidMount和setState获取父级的高度,但componentDidMount仅在父级div第一次渲染时才被调用。
而且我不能使用ReactDOM.findDOMNode(this).clientHeight内部render()函数。
为简化起见,这些步骤如下:
有任何想法吗?
这是一段代码:
import React, { Component } from 'react';
import Div2 from './Div2';
class Div1 extends Component {
constructor(props){
super(props);
this.state = {
height: 0
};
}
componentDidMount() {
var height = (ReactDOM.findDOMNode(this).clientHeight);
this.setState({height: height})
}
render() {
return(
<div className='Div1'>
<Div2 height={this.state.height}/>
</div>
);
}
}
export default Div1;
Run Code Online (Sandbox Code Playgroud)
您必须在3个地方state以新高度更新父母的位置:
componentDidMount在第一次render(div实际是父母的第一次出现)之后会被调用。componentDidUpdaterender由props和state更新引起的-ing 后调用。仅当您实际使用任何工具时props,才需要这样做,并且它们的更新可能会导致div的高度变化。您必须使用方法内部refs获取parent div的DOM元素render。之后,您可以在componentDidMount和中使用它componentDidUpdate(请检查React Component Lifecycle文档)。
将所有内容组合在一起会产生以下代码,其中Foo将根div的高度传递给Bar:
class Bar extends React.Component {
render() {
return (
<div className='bar' style={{height: `${this.props.height / 2 }px`}} />
);
};
};
class Foo extends React.Component {
constructor() {
super();
this.state = { height: 0 };
this.updateHeight = this.updateHeight.bind(this);
}
componentDidMount() {
this.updateHeight();
window.addEventListener("resize", this.updateHeight);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateHeight);
}
componentDidUpdate() {
this.updateHeight();
}
updateHeight() {
if (this.state.height != this.div.clientHeight)
this.setState({ height: this.div.clientHeight })
}
render() {
return (
<div ref={ div => { this.div = div; } } className='foo'>
<Bar height={this.state.height} />
</div>
);
}
}
ReactDOM.render(<Foo/>, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)
工作示例可以在这里找到。