[英]react-select onChange event does not render with props
我正在使用 select-react 库-> https://react-select.com/home
我已经设法将选项映射到我需要从 itemList 中的各个项目。 下拉列表确实注册了所选选项,但是我的最终目标是让我的条形图呈现所选选项的正确数据。
/**
* Produces a filter list for item sales cards
* @param {*} props
* @returns the filter list of item names along with their ids
*/
export const ItemSelection = (props) => {
const { onChangeValue, itemList } = props;
if (itemList.length === 0) return <></>;
return (
<UncontrolledDropdown>
<Select
options={itemList.map((item) => {
return {
label: item.name,
value: item,
key: item.itemID,
};
})}
onChange={(item)=>onChangeValue(item)}
placeholder="ITEM"
/>
</UncontrolledDropdown>
);
};
itemSelection 在这里被使用:
const [itemID = '1', setItemID] = useState('1');
const [itemName = '', setItemName] = useState('');
const [itemListID = [], setItemListID] = useState([]);
<ItemSelection
onChangeValue={(item) => {
setItemID(item.itemID);
setItemName(item.name);
}}
itemList={itemListID}
/>
onChangeValue 是将所选选项注册到条形图的选项。 map onChangeValue 有没有?
这取决于您实际上期望从使用 ItemSelection 的父元素中得到什么参数。 也就是说,它看起来也像 Select 采用 function ,它采用字符串类型的操作和选项值作为第二个参数。 然后,选定的值将出现在第二个参数中。
如果您只关心价值,那么您需要以下代码行中的内容。 在那一点上,您将获得传递给onChangeValue
的选定字符串值,我想这是您想要的,而不会从祖先组件中看到 function 定义。
更新:
select 代码可以将整个选项 object 作为第二个参数。
export const ItemSelection = (props) => {
const { onChangeValue, itemList } = props;
if (itemList.length === 0) return null;
return (
<UncontrolledDropdown>
<Select
options={itemList.map((item) => ({
label: item.name,
value: item.name, // note a change from your code here; it would have been an object otherwise
key: item.itemID,
}))}
onChange={(item)=>onChangeValue(item)}
placeholder="ITEM"
/>
</UncontrolledDropdown>
);
};
在父组件中
// note the changes here where I deleted the assignments
const [itemID, setItemID] = useState('1');
const [itemName, setItemName] = useState('');
const [itemListID, setItemListID] = useState([]);
<ItemSelection
onChangeValue={(option) => {
setItemID(option.key);
setItemName(option.value);
}}
itemList={itemListID}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.