【问题标题】:how can I dynamically attach sidebar components to multiple instances of sidebar?如何将侧边栏组件动态附加到侧边栏的多个实例?
【发布时间】:2019-01-01 10:34:11
【问题描述】:

我是 React 新手,在构建设计时遇到了问题。

我有一个名为 SideBar 的组件。我使用这个组件两次,在页面的每一侧。

问题是我想为 SideBar 组件的每个实例添加不同的组件。这些将是各种项目等的列表。我假设我可以下一个组件标签,但侧边栏组件不输出。

import React, { Component } from "react";
import SideBar from "./WorkspaceComponents/SideBar";
import ScrollerBox from "./WorkspaceComponents/SideBarComponents/ScrollerBox";

class Workspace extends Component {
  render() {
    return (
      <main className="reely-workspace">
        <SideBar position="SideBarLeft">
          <ScrollerBox />
        </SideBar>
        <SideBar position="SideBarRight" />
      </main>
    );
  }
}

export default Workspace;

【问题讨论】:

    标签: reactjs components


    【解决方案1】:

    您的侧边栏组件应该接收一个 children 属性并将其渲染出来。

    类似这样的:

    class Sidebar extends Component {
      render() {
        const {children} = this.props;
        return (
          <div className="sidebar">
            <h1>Sidebar</h1>
            {children}
          </div>
        )
      }
    }
    

    查看这篇关于 React 文档的帖子,了解如何编写 React 组件:https://reactjs.org/docs/composition-vs-inheritance.html

    【讨论】:

      【解决方案2】:

      你可以让你的SideBar 组件成为一个包装器组件,用于包装其中给出的内容。

      让 SideBar 组件成为 Wrapper 组件:

      class Sidebar extends Component {
        render() {
          return (
            <div className="sidebar">
              // You can add any custom element here //
              {this.props.children}
            </div>
          )
        }
      }
      

      您在 SideBar 组件中传递的所有元素现在都将呈现为 SideBar 的一部分及其包含的内容。

      使用包装器组件的方式:

      <SideBar>
         <Content1></Content1>
         <Content2></Content2>
         <Content3></Content3>
      </SideBar>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-13
        • 1970-01-01
        • 2017-10-29
        • 1970-01-01
        • 2020-10-22
        相关资源
        最近更新 更多