可以获取不同组件的父组件

时间:2018-10-14 09:14:43

标签: reactjs

我有一个<Panel/>组件,该组件必须具有不同的变化组件。

例如,一次-<Panel/>需要包含一个<Dropdown/>组件,第二次是<TextInput/>,第三次是<Checkbox/>

如何使此<Panel/>组件获得不同的组件?

<Panel/>组件:

import React from "react";
import { css } from "emotion";
import colors from '../../styles/colors';
import PanelHeader from "./PanelHeader";

export default function Panel({ active, panelHeader}) {
    const styles = css({
        borderRadius: 4,
        backgroundColor: "white",
        border: `1px solid ${ active ? colors.blue : colors.grayLight }`,
        width: 540,
        padding: 32,

    });
    return (
        <div className={styles}>
            {panelHeader && <PanelHeader headerType={panelHeader} />}
        </div>
    );
}

小组的故事:

import React from "react";
import { storiesOf } from "@storybook/react";

import Panel from "../components/Panel";
import colors from '../styles/colors';

import PanelHeader from "../components/Panel/PanelHeader";

storiesOf("Panel", module)
    .add("Default", () => (
        <Panel></Panel>
    ))
    .add("Active", () => (
        <Panel active></Panel>
    ))

storiesOf("Panel/PanelHeader", module)
    .add("Default", () => (
        <PanelHeader headerType="Identity document" color={colors.gray}>1</PanelHeader>
    ))
    .add("Active", () => (
        <PanelHeader headerType="Identity document" color={colors.blue}>1</PanelHeader>
    ))

1 个答案:

答案 0 :(得分:1)

您可以更改Panel以接受children道具,将其传递到渲染<Panel>的位置,然后传递相应的组件。

例如:

// PropType for children is `PropTypes.node`
export default function Panel({ active, panelHeader, children}) {
    // ...
    return (
        <div className={styles}>
            {children}
        </div>
    );
}

// ...

<Panel><Dropdown /></Panel>

// or

<Panel><TextInput /></Panel>

或者,您可以传入组件类/函数并将其呈现在内部:

export default function Panel({ active, panelHeader, ChildComponent}) {
    // ...
    return (
        <div className={styles}>
            {/* This is like any other component, 
                you can pass in props as usual. */}
            {/* It's important for the name to start with an uppercase letter, 
                otherwise the JSX compiler will turn this in a string! */}
            <ChildComponent />
        </div>
    );
}

// ...

<Panel ChildComponent={Dropdown}></Panel>

// or

<Panel ChildComponent={TextInput}></Panel>

此模式称为组件组成。您可以在React文档中阅读更多内容:https://reactjs.org/docs/composition-vs-inheritance.html