以下代码显然不起作用,但是我的想法是,我想根据子组件的clientHeight进行条件渲染,不确定是否可能
class App extends Component {
constructor() {
super();
this.comp = {};
this.state = {
clientHeight: 0
};
}
componentDidMount() {
console.log(this.comp)
this.setState({
clientHeight: this.comp.clientHeight
});
}
render() {
return (
<div>
<Hello name={this.state.name} ref={comp => this.comp = comp}/>
{
this.state.clientHeight > 100 ? <ComponentA /> : <ComponentB />
}
</div>
);
}
}
事实证明,@ Dane的想法帮助了我。用componentDidUpdate
钩。这个实现器是我想要的,但是它每次渲染两次,一次分配给ref,然后将更新更改为新的clientHeight,然后根据新的clientHeight再次渲染。不知道是否有更好的方法。
class App extends Component {
constructor() {
super();
this.comp = {};
this.state = {
clientHeight: 0
};
}
componentDidUpdate(prevProps){
if(prevProps !== this.props){
this.setState({
clientHeight: this.comp.clientHeight
})
}
}
render() {
return (
<div>
<Hello name={this.state.name} ref={comp => this.comp = comp}/>
{
this.state.clientHeight > 100 ? <ComponentA /> : <ComponentB />
}
</div>
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句