reactjs - 可以获取不同组件的父组件
问题描述
我有一个<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>
))
解决方案
您可以更改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
推荐阅读
- php - WP 样式/脚本不加载
- python - 在段落中搜索特定字符串
- azure - 如何为 Azure Pipelines Docker 任务指定当前目录?
- python-3.5 - 这是我正在尝试对嵌套列表进行切片,但我得到以下输出。解释?
- in-app-purchase - Costco 如何避免使用 Apple In App Purchase
- laravel - Laravel 运行一组带有特定守卫的中间件
- c# - UWP Xaml 旋转复选框修剪标签
- php - HTML 表单提交按钮显示代码而不是执行它
- python - 具有两个输出的 Keras MSE 损失
- reactjs - 如何在 React 组件中更新 Signalr 数据