【发布时间】: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