React 仅在渲染 Child 时才渲染父级

Mic*_*elH 5 javascript reactjs

我想知道是否有办法只在渲染子组件时渲染父组件,反之亦然。如果你用谷歌搜索标题,你会发现很多条目,但对我的情况没有任何作用,因为我的元素不是undefinednull,例如。想象一个家长:

class Parent extends React.Component {
  constructor(props){
    super(props);
  }

  render() {
    return (
      <div>
        <div className="container">
          {this.props.children}
        </div>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

以下子项可能取决于某些设置。例如,仅显示布尔值是否为真。

class Child extends React.Component {
      constructor(props){
        super(props);
        const showChild = Settings.get(...);
        this.state = {
           visible:showChild
        }
      }

      render() {
        const showHello = this.state.visible ? <div>Hello</div> : "";
        return (
          <div>{showHello}</div>
        );
      }
    }
Run Code Online (Sandbox Code Playgroud)

在我的布局中,我像这样搭建脚手架:

class Layout extends React.Component {
  constructor(props){
    super(props);
  }

  render() {
    return (
      <Parent>
        <Child />
      </Parent>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Parent如果该Child元素未呈现,是否可以卸载?谢谢你。

更新:用例是,如果我想这ParentChild是在一个LayoutParent具有较大的填充或保证金的容器类,因为它仍然是在组件树。如果 Child 没有被渲染,Layout 中会留下一个很大的间隙,它看起来很奇怪。

Jor*_*rix -2

Parent您可以通过检查组件是否有子组件来有条件地渲染组件。

用于this.props.children.length查看是否有,如果有则正常渲染,如果没有则返回空元素。