React PropTypes:不同对象形状的数组
React PropTypes: An array of different object shapes
如何为包含一组不同对象形状的数组声明 proptype 定义?例如,
如果我有一个组件,例如 EmailRenderer
,它采用一个名为 sections
的道具,它是一个不同对象的数组,每个对象都有一个唯一的类型和相关的属性。
const sections = [
{
type: "h1",
copy: "Header!",
},
{
type: "p1",
copy: "lots of copy....",
},
{
type: "image-main",
src:
"http://www.some-image.com",
alt: "blah",
},
{
type: "button",
buttonType: "secondary",
copy: "Watch now!",
href: "#",
},
{
type: "p1",
copy: "more copy...",
},
];
// ...
class EmailRenderer extends React.Component {
// ...
}
//...
EmailRenderer.propTypes = {
sections: PropTypes.arrayOf(
// ???
)
}
<EmailRenderer sections={sections} />
为每个 "types" 声明 类,我们称它们为 TypographyElement
(复制)、MediaElement
(src)、ButtonElement
(href) .
然后 sections
道具可以声明为
sections : PropTypes.arrayOf(
PropTypes.oneOf(
[
PropTypes.instanceOf(TypographyElement),
PropTypes.instanceOf(MediaElement),
PropTypes.instanceOf(ButtonElement),
...
]
)
);
如何为包含一组不同对象形状的数组声明 proptype 定义?例如,
如果我有一个组件,例如 EmailRenderer
,它采用一个名为 sections
的道具,它是一个不同对象的数组,每个对象都有一个唯一的类型和相关的属性。
const sections = [
{
type: "h1",
copy: "Header!",
},
{
type: "p1",
copy: "lots of copy....",
},
{
type: "image-main",
src:
"http://www.some-image.com",
alt: "blah",
},
{
type: "button",
buttonType: "secondary",
copy: "Watch now!",
href: "#",
},
{
type: "p1",
copy: "more copy...",
},
];
// ...
class EmailRenderer extends React.Component {
// ...
}
//...
EmailRenderer.propTypes = {
sections: PropTypes.arrayOf(
// ???
)
}
<EmailRenderer sections={sections} />
为每个 "types" 声明 类,我们称它们为 TypographyElement
(复制)、MediaElement
(src)、ButtonElement
(href) .
然后 sections
道具可以声明为
sections : PropTypes.arrayOf(
PropTypes.oneOf(
[
PropTypes.instanceOf(TypographyElement),
PropTypes.instanceOf(MediaElement),
PropTypes.instanceOf(ButtonElement),
...
]
)
);