简体   繁体   中英

How to create React component with components inside it?

I need something like this:

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

I noticed that some React UI frameworks have an implementation of this feature, eg Ant Design ( <Layout /> ), Semantic UI ( <Button /> ), and Blueprint ( <Tabs2 /> ).
I have tried to find how to do the same component but found an article about dot notation . With it, I can use child components, but can't use a parent as a component.
So, what is the appropriate way to create components that can be used in JSX with child components as well?

Clarification. What I have:

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

What I want:

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

Well you're so close! you just need to assign the child to the parent as a property.

Component.Child = Child;

Now you can use <Component /> and <Component.Child /> as you desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM