【问题标题】:Cannot use a map method into a React component using TypeScript无法使用 TypeScript 将 map 方法用于 React 组件
【发布时间】:2023-01-26 03:04:22
【问题描述】:

我正在使用 React 和 TypeScript。尝试映射包含对象的数组 - 在本例中为 shoppingItems

type Props = {
  shoppingItems: [{
    id: (null | string),
    name: (null | string),
    isComplete: (null | boolean),
  }],
  toggleItem: any;
}

export const ShoppingList: Function = (
  {shoppingItems}: Props,
  {toggleItem}: Props,
) => {
  return shoppingItems.map((Item: any) => {
    return <Item Item={Item} key={Item.id} toggleItem={toggleItem} />;
  });
};

这是 App.js

const App: React.FC = () => {
  const [shoppingItems, setShoppingItems] = useState<Item>([]);
  const itemNameRef = useRef<null | HTMLInputElement>(null);

  const toggleItem = (id: any) => {
    const newShoppingItem = [...shoppingItems];
    const Item = newShoppingItem.find((Item) => Item.id === id);
    Item.isCompleted = !Item.isCompleted;
    setShoppingItems(newShoppingItem);
  };

  const handleAddItem = (e: any) => {
    if (itemNameRef.current) {
    const itemNameCurrent = itemNameRef.current
    const name: (null | string | HTMLInputElement) = itemNameCurrent.value;
    setShoppingItems((prevItems: any) => {
      return [...prevItems, { id: uuidv4(), name: name, isCompleted: false }];
    });
    itemNameRef.current.value = '';
  }
  };

  return (
    <div className="App">
      <ShoppingList shoppingItems={shoppingItems} toggleItem={toggleItem} />
      <div>
        <input ref={itemNameRef} type="text"></input>
        <br />
        <button onClick={handleAddItem}>Add</button>
      </div>
    </div>
  );
};

单击按钮后我得到的是:React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

目的是显示数组内对象的选定值。

我还有 Item 组件负责选择值,但到目前为止没有返回任何错误。

如何使 shoppingItems 组件期望对象并将 .map 作为方法读取?

我试图将类型分配给函数内的道具。然后是功能组件(而不是 Props),但有点忙,我每次都要处理语法错误。我希望我能以某种方式将一组对象传递给shoppingList

【问题讨论】:

    标签: reactjs typescript react-functional-component


    【解决方案1】:

    您的 .map 元素名为 Item: any。当你 return &lt;Item Item 不是一个组件,而是一个 shoppingItem 对象。对象不是有效元素,因此您会看到 invalid type 错误。

      return shoppingItems.map((Item: any) => {
        return <Item Item={Item} key={Item.id} toggleItem={toggleItem} />;
      });
    

    你提到,你有一个 Item 组件,所以我想这只是一个名称冲突。

    尝试将 Item: any 重命名为其他名称。

      return shoppingItems.map((element: any) => {
        return <Item Item={element} key={element.id} toggleItem={toggleItem} />;
      });
    

    【讨论】:

      猜你喜欢
      • 2021-08-31
      • 1970-01-01
      • 2019-11-11
      • 2020-06-15
      • 1970-01-01
      • 2021-06-30
      • 2020-02-17
      • 1970-01-01
      • 2021-03-05
      相关资源
      最近更新 更多