【问题标题】:How to create React component with components inside it?如何创建包含组件的 React 组件?
【发布时间】:2017-10-25 10:13:38
【问题描述】:

我需要这样的东西:

<Component>
    <Component.Child1>Test 1</Component.Child1>
    <Component.Child2>Test 2</Component.Child2>
</Component>

我注意到一些 React UI 框架具有此功能的实现,例如Ant Design (&lt;Layout /&gt;)、Semantic UI (&lt;Button /&gt;) 和 Blueprint (&lt;Tabs2 /&gt;)。
我试图找到如何执行相同的组件,但发现了一篇关于 dot notation 的文章。有了它,我可以使用子组件,但不能使用父组件。
那么,创建可在 JSX 中与子组件一起使用的组件的适当方法是什么?

澄清。我有什么:

const Component = (props) => (<div className="someClass">{props.children}</div>)
const Child = () => (<div>Child content</div>)

我想要什么:

const App = () => (
    <Component>
        <Component.Child>Test 1</Component.Child>
    </Component>
)

【问题讨论】:

  • “但不能使用父级作为组件”是什么意思
  • 无法理解“也可以在 JSX 中与子组件一起使用”的意思。你能详细说明一下吗?
  • const Component = () =&gt; (&lt;div&gt;{props.children}&lt;/div&gt;) const Child = () =&gt; (&lt;div&gt;{props.children}&lt;/div&gt;) const App = () =&gt; ( &lt;Component&gt; &lt;Child&gt;Test 1&lt;/Child&gt; &lt;/Component&gt; )怎么样

标签: javascript reactjs


【解决方案1】:
const Component = (props) => (<div className="someClass">{props.children}</div>)
const Child = () => (<div>Child content</div>)

好吧,你离得太近了!您只需要将孩子作为属性分配给父母。

Component.Child = Child;

现在您可以随意使用&lt;Component /&gt;&lt;Component.Child /&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2018-08-29
    • 2021-04-15
    相关资源
    最近更新 更多