我有一个动画组件,它根据 Prop (真或假)向上/向下滑动。我正在使用 maxHeight: 0 来隐藏组件(转换是用 CSS 完成的),这是作为 prop 传递的默认状态。对于打开的样式,我使用的 maxHeight 比需要的大得多,只是为了确保内容适合。打开后,我可以通过 ref 获取它的高度并相应地设置 maxHeight。
export default class AnimatedInput extends React.Component {
constructor (props) {
super(props);
this.state = {
height: 600
}
}
componentDidUpdate(prevProps) {
var height = this.refs.inputNode ? this.refs.inputNode.clientHeight : height;
console.log(height);
if (this.props.open === false && prevProps.open === true) {
this.setState({height: height});
}
}
render () {
var {height} = this.state;
let test = this.props.open ? 'boxVisible' : 'boxHidden';
var styles = {
boxHidden: {
...
maxHeight: 0,
},
boxVisible: {
....
maxHeight: height,
}
}
return (
<div style={styles[test]} ref="inputNode">
{this.props.children}
</div>
)
}
}
这种方法有两个问题:
第一次打开和关闭时由于 maxHeight 大于应有的值而不流畅(也许将打开的渲染到屏幕外并先获取其高度?)
如果它在完全打开之前关闭,高度将低于应有的高度(我想这很容易解决 - 只需要停止更新高度值)。
我走在正确的轨道上吗?你会如何解决这些问题?我应该坚持使用 CSS 还是完全在 JS 中进行转换。感谢您的建议!
最佳答案
您正在寻找 ReactCSSTransitionGroup
。我用这个来做和你完全一样的事情。
关于javascript - 在显示在屏幕上之前获取渲染元素的高度(ReactJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46497260/