[英]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.