首页 > 解决方案 > 可以获取不同组件的父组件

问题描述

我有一个<Panel/>组件必须获得不同的变化组件。

例如第一次 -<Panel/>需要包含一个<Dropdown/>组件,第二次是 a <TextInput/>,第三次是 a <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>
    ))

标签: reactjs

解决方案


您可以更改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


推荐阅读