将对象数组渲染为故事书中的子道具时,对象作为 React 子对象无效
Objects are not valid as a React child when rendering an array of objects as children prop in storybook
我有一个组件接收 children
prop 作为对象数组并呈现它们。
type Item = {
id: number;
name: string;
};
interface IProps {
children: Item[];
}
const List: React.FC<IProps> = ({ children }) => {
return (
<ul>
{children.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
我为这个组件创建了一个故事,如下所示。
const Template: ComponentStory<typeof List> = (args) => <List {...args} />
export const Default = Template.bind({});
Default.args = {
children: [
{ id: 0, name: "Apple" },
{ id: 1, name: "Google" },
{ id: 2, name: "Facebook" },
],
};
这个我也试过了
export const Default: ComponentStory<typeof List> = () => (
<List>
{[
{ id: 0, name: "Apple" },
{ id: 1, name: "Google" },
{ id: 2, name: "Facebook" },
]}
</List>
);
但无论哪种方式,故事书都会抛出以下错误。
Objects are not valid as a React child (found: object with keys {id, name}). If you meant to render a collection of children, use an array instead.
我做错了什么?
使用不同的道具而不是 children
道具。
const List: React.FC<IProps> = ({ items }) => {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
我有一个组件接收 children
prop 作为对象数组并呈现它们。
type Item = {
id: number;
name: string;
};
interface IProps {
children: Item[];
}
const List: React.FC<IProps> = ({ children }) => {
return (
<ul>
{children.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
我为这个组件创建了一个故事,如下所示。
const Template: ComponentStory<typeof List> = (args) => <List {...args} />
export const Default = Template.bind({});
Default.args = {
children: [
{ id: 0, name: "Apple" },
{ id: 1, name: "Google" },
{ id: 2, name: "Facebook" },
],
};
这个我也试过了
export const Default: ComponentStory<typeof List> = () => (
<List>
{[
{ id: 0, name: "Apple" },
{ id: 1, name: "Google" },
{ id: 2, name: "Facebook" },
]}
</List>
);
但无论哪种方式,故事书都会抛出以下错误。
Objects are not valid as a React child (found: object with keys {id, name}). If you meant to render a collection of children, use an array instead.
我做错了什么?
使用不同的道具而不是 children
道具。
const List: React.FC<IProps> = ({ items }) => {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};