gpt4 book ai didi

javascript - 如何在不渲染子组件的情况下根据子组件大小更改 React 父组件大小?

转载 作者:行者123 更新时间:2023-11-30 14:16:33 25 4
gpt4 key购买 nike

我创建了一个 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}>
&times;
</a>
<this.state.childComponent onSize={this.OnSize}/>
</div>
</div>
)
}
}

初始宽度和高度设置为 0。因此无法正确呈现。那么有什么办法可以在父组件获取大小之前隐藏子组件或者避免渲染呢?

编辑:在渲染子组件之前我们无法获取尺寸。那么有什么技巧可以完成这项工作。只需要正确弹出一个组件即可。

编辑 2:这是 PropsBuilder.tsx,它调用 Popup.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;

最佳答案

实际上,这看起来像是更一般的 DOM/JavaScript 问题。

考虑这样的情况:

const span = document.createElement('span');
span.innerText = 'hello';
span.getBoundingClientRect() // -> { width: 0, height: 0, top: 0, … }

这表明您不知道元素的尺寸,直到它在 DOM 中(在 react 中呈现);

document.body.appendChild(span);
span.getBoundingClientRect(); // -> {width: 50, height: 16,  …}

在这种情况下我给你的建议是:

  1. 子组件应该接受父组件的属性(函数)
  2. 使用 React 的“ref”功能查找子元素的实际尺寸
  3. 调用“componentDidMount”中的函数(如果子组件可以动态更改,则使用 componentDidUpdate),将其传递给子组件尺寸。

如果您无权访问子组件。你可以这样包装它:

// Popup.tsx

class Popup .... {
...
render() {
<Measurer>{this.props.children}</Measurer>
}
}

并在其中实现获取维度的逻辑。 Measurer 是 Popup 的直接子项,它们的通信可以由您控制。

关于javascript - 如何在不渲染子组件的情况下根据子组件大小更改 React 父组件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53483850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com