React:如何覆盖子组件

时间:2017-11-28 14:22:11

标签: reactjs

覆盖子组件的最佳方法是什么?

  1. 检查 this.props.children != null
  2. 使用 props
  3. 传递组件
  4. 示例组件

    class ParentComponent extends Component {
      render() {
        <div>
          <ChildComponent />
        </div>
      }
    }
    

    解决方案1 ​​

    class ParentComponent extends Component {
      render() {
        <div>
          {this.props.children ? this.props.children : <DefaultChildComponent/>}
        </div>
      }
    }
    
    <ParentComponent><MyChildComponent/></ParentComponent>
    

    解决方案2

    class ParentComponent extends Component {
      render() {
        <div>
          {this.props.child}
        </div>
      }
    }
    Parent.defaultProps = { child: <DefaultChildComponent /> }
    
    const myChildComponent = <MyChildComponent/>
    <ParentComponent child={myChildComponent}/>
    

    解决方案3?

1 个答案:

答案 0 :(得分:0)

当您检查this.props.children但是然后渲染其他组件而不是children时,您所问的内容会有些混乱。

我原以为最好的方式就是;

class ParentComponent extends Component {

  render() {

    <div>       
       {
           this.props.children
           ? this.props.children
           : <DefaultChildComponent />
       }
    </div>
  }
}

然后用它作为;

<ParentComponent />

这只是呈现您的默认子组件

<ParentComponent><div>Can Be Any Child</div></ParentComponent>

你可以传递任何组件就像这个孩子一样,然后将被渲染。

相关问题