gpt4 book ai didi

javascript - 解析错误消息 "react-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a function"

转载 作者:行者123 更新时间:2023-12-05 05:54:32 25 4
gpt4 key购买 nike

我不知道为什么,但当我更改选择器中的选项时,我不断收到此错误。“react-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a function”:(

    import React from "react";
import Product from "./Product";
import ListGroup from "./listGroup";

export default function Main(props) {
const { products, onAdd, categories } = props;

const handleCategorySelect = () => {
console.log("Click");
};

return (
<main className="block col-2">
<ListGroup items={categories} />
<h2>Products</h2>
<div>
{products.map((product) => (
<Product
key={product.id}
product={product}
onAdd={onAdd}
onItemSelect={handleCategorySelect}
></Product>
))}
</div>
</main>
);
}

我的 listGroup.jsx 是:

import React from "react";

function ListGroup(props) {
const { items, onItemSelect } = props;
return (
<form>
<select
value=""
id="category"
name="category"
onChange={() => onItemSelect()}
>
<option hidden value="">
Choose here
</option>
{items.map((item) => (
<option key={item._id}>{item.name}</option>
))}
</select>
</form>
);
}

export default ListGroup;

还有如何将项目对象传递给 onChange ?我的意思是,如果它是一个列表组,我会选择:

<ul className="list-group">
{items.map(item => (
<li
onClick={() => onItemSelect(item)}
key={item[valueProperty]}
className={
item === selectedItem ? "list-group-item active" : "list-group-item"
}
>
{item[textProperty]}
</li>
))}
</ul>

但是对于选择和选项我不知道该怎么做。

最佳答案

是因为你没有把函数传给ListGroup组件

export default function Main(props) {
...
<ListGroup items={categories} />

但是你在改变时调用它

function ListGroup(props) {
...
<select
value=""
id="category"
name="category"
onChange={() => onItemSelect()}
>

试试这个

<ListGroup items={categories} onItemSelect={handleCategorySelect} />

下面是如何将 select 的值传递回父组件:

function ListGroup({ items, onItemSelect }) {
function handleItemChange(e) {
onItemSelect(e.target.value);
}

return (
<div>
<select onChange={handleItemChange}>
{items.map((item) => <option key={item.name}>{item.name}</option>)}
</select>
</div>
);
}

function Main() {
const items = [
{ name: 'apple' },
{ name: 'milk' },
{ name: 'bread' },
{ name: 'cheese' }
];

function handleListSelect(val) {
console.log(`I selected ${val}`);
}

return (
<div>
<ListGroup items={items} onItemSelect={handleListSelect} />
</div>
);
}

function App() {
return (
<div>
<Main />
</div>
);
}

ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>

关于javascript - 解析错误消息 "react-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69641277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com