【问题标题】:Objects are not valid as a React child (found: object with keys {})/If you meant to render a collection of children, use an array instead. Help me?对象作为 React 子级无效(找到:带有键 {} 的对象)/如果您打算渲染子级集合,请改用数组。帮我?
【发布时间】:2021-11-25 13:14:42
【问题描述】:

我正在使用带有 react.tsx 的 storyBook,我从标题中得到了这个错误。我试图看看出了什么问题,但没有任何成功。这是我的 3 个脚本

import React from "react";
import "./Button.css";

export interface IButtonProps {
  variant: "primary" | "secondary" | "success" | "danger";
  title: string;
}

const Button: React.FC<IButtonProps> = (variant, title) => {
  return <button className={`button ${variant}`}>{title}</button>;
};

export default Button;

我不会添加 CSS...

import React from "react";
import Button from "./Button";
import { Meta } from "@storybook/react";

export default {
  title: "Button",
  component: Button,
} as Meta;

export const Primary: React.VFC<{}> = () => (
  <Button variant="primary" title="Primary"></Button>
);
export const Secondary: React.VFC<{}> = () => (
  <Button variant="secondary" title="Secondary">
    Secondary
  </Button>
);
export const Success: React.VFC<{}> = () => (
  <Button variant="success" title="Success">
    Success
  </Button>
);
export const Danger: React.VFC<{}> = () => (
  <Button variant="danger" title="Primary">
    Danger
  </Button>
);

当我尝试运行它时,我得到了这个:enter link description here

可能是什么问题?

【问题讨论】:

    标签: reactjs typescript storybook


    【解决方案1】:

    问题在于Button 功能组件中的参数。您在括号 variant, title 中传递了两个参数。但是,当您定义 Props 对象时,您应该只传递一个参数,即 props(无论您如何命名,为了清楚起见,我总是将其称为 props)。像这样:

    const Button: React.FC<IButtonProps> = (props) => {
        return <button className={`button ${props.variant}`}>{props.title}</button>;
    };
    

    这样,React 会在预定义的对象中加载传递的 props,而你的参数是哪个。因此,您需要在 return 中调用 props 的每个属性。出现错误是因为variant 最终成为道具对象(道具被传递给第一个参数),而title 最终成为一个空对象。当您将对象作为按钮标题传递时,应用程序会抛出错误,因为它需要字符串而不是空对象。您可以在返回按钮之前console.log(vairant, title)自行查看。

    【讨论】:

      猜你喜欢
      • 2021-01-02
      • 2019-06-14
      • 2020-06-24
      • 2021-09-28
      • 2020-08-12
      • 2019-10-12
      • 2020-10-18
      • 2021-11-18
      • 2020-12-22
      相关资源
      最近更新 更多