【发布时间】:2019-04-28 06:14:03
【问题描述】:
我创建了一个 React 组件,它接受任何组件并将其呈现为弹出窗口。 父组件接收要呈现(弹出)的组件。渲染组件在这里是子组件,它使用 react-sizeme 获取其大小并传回父组件。 父组件必须取子组件的尺寸,所以调整它的高度和宽度。这是代码:
class Popup extends React.Component<IPopupProps,IComponent>{
constructor(props:IPopupProps){
super(props);
this.state={
childComponent:this.props.children,
style:{
height:0,
width:0
}
}
}
// This function runs two times, before and after rendering child component
// & so have an improper visualization as the size is changed twice here
public OnSize = (size:any) =>{
const width = size.width +20;
const height =size.height+20;
this.setState({
style:{height,
width }
})
}
public render(){
return(
<div className='popup'>
<div style={this.state.style} className='popup-content'>
<a className="close" onClick={this.props.onExit}>
×
</a>
<this.state.childComponent onSize={this.OnSize}/>
</div>
</div>
)
}
}
初始宽度和高度设置为 0。因此无法正确渲染。那么有什么办法可以在父组件获得大小之前隐藏子组件或避免其渲染?
编辑:在渲染子组件之前,我们无法获得大小。那么有什么技巧可以完成这项工作。只需正确弹出一个组件即可。
编辑 2:这是调用 Popup.tsx 并将组件发送为子组件显示的 PropsBuilder.tsx
class PopupBuilder extends React.Component<IPopupBuilderProps, IPopup>{
constructor(props:IPopupBuilderProps){
super(props);
this.state = {
showPopup:false
}
}
public togglePopup = () =>{
this.setState({
showPopup:!this.state.showPopup
})
}
public render (){
return(
<React.Fragment>
<button onClick={this.togglePopup}>{this.props.trigger}</button>
<React.Fragment>
{this.state.showPopup?<Popup onExit={this.togglePopup} >{this.props.component}</Popup>:null}
</React.Fragment>
</React.Fragment>
)
}
}
export default PopupBuilder;
【问题讨论】:
-
shouldComponentupdate 钩子是否适用于这种情况
-
我同时也在搜索这个。实际上,在渲染之前我们无法获得组件的大小。我猜我们不能使用 shouldComponentUpdate 因为它根本不会被渲染。所以现在的问题是如何正确地将任何组件显示为弹出窗口。
-
首先将其渲染到屏幕外(即视口之外),获取测量值,然后将其渲染到屏幕上。
-
@JaredSmith 这个建议确实有效。我将它与舍甫琴科的回答结合起来
-
@NikhilPatil 它类似于游戏开发中的一个古老的技巧。由于游戏的帧预算只有这么少(16 毫秒),因此您通常会将下一帧“绘制”到内存中的图像缓冲区(快速且便宜),然后将整个内容一次全部交换为屏幕上的内容而不是绘制场景中的每个对象都在递增(缓慢/昂贵)。
标签: javascript reactjs