【问题标题】:Use react component as a child or from within the render function of a React component将 React 组件用作子组件或在 React 组件的渲染函数中使用
【发布时间】:2019-08-27 05:35:48
【问题描述】:

有时我们在 react 组件的 render 函数中使用 React 组件,如下所示:

render() {
  return(
    <div>
      ...
      <MYReactComponent/>
      ...
    </div>
  )
}

有时我可以将 react 组件用作另一个组件的子组件:

<ParentReactComp>
     ...
     <MYReactComponent/>
    ...

</ParentReactComp>

一种方式比另一种方式有什么优势?

【问题讨论】:

    标签: reactjs ecmascript-6 jsx


    【解决方案1】:

    当您直接在 reander 函数中添加一个组件时,您将在您添加该组件的位置上获得该组件。

    但是当你使用这个时,

    <ParentReactComp>
        ...
         <MYReactComponent/>
        ...
    
    </ParentReactComp>
    

    在您的 ParentReactComp 组件中,您需要使用

    显式添加您的子组件
    {this.props.children}
    

    Demo

    【讨论】:

      【解决方案2】:

      在 render 中声明单个组件可以让你用 props 调用简单的 react 组件。

      <div>
       ...
       <MYReactComponent/>
       ...
      </div>
      

      您可能希望在需要时将组件包装在父组件中

      <ParentReactComp>
           ...
           <MYReactComponent/>
          ...
      
      </ParentReactComp>
      

      1) 包装器html

      2) 将一些数据传递给MyReactComponent 用于组合模式或将其用作容器。

      3) 您可能希望使用{this.prop.children}ParentReactComp 中获取MyReactComponent

      最后两者都是 react 组件,你可以根据需求将一个组件封装到另一个组件中。

      希望对你有帮助!!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-12
        • 2018-06-16
        • 1970-01-01
        • 2017-07-23
        • 2017-03-14
        • 2021-03-16
        • 1970-01-01
        • 2016-08-07
        相关资源
        最近更新 更多