从语义UI下拉项中检索值?



是否有办法检索下拉菜单项的值?当on-click处理程序被调用时,它不返回值,而是返回文本和IMG组件。而且附加在下拉菜单上的onchange处理程序永远不会被触发

import React from "react";
import { Dropdown, Item } from "semantic-ui-react";
import { connect } from "react-redux";
import "./currency.style.css";
const CurrencyConverter = ({ currencyDetails, initialData }) => {
const handleSelection = (e) => {
alert();
};
return (
<div className="currency-form">
<div className="selected-Country">
<img src={initialData.flag} width="30px" height="30px" />
</div>
<Dropdown
inline
text={initialData.currency}

>
<Dropdown.Menu

>
{currencyDetails.map((item) => (
<Dropdown.Item
key={Math.random()}
text={item.currencyName}
image={item.flag}
style={{ height: "70px", fontSize: "17px" }}
onClick={(event, item) => {
console.log(item);
}}
/>
))}
</Dropdown.Menu>
</Dropdown>
</div>
);
};
const mapStateToProps = ({ currency: { currencyDetails } }) => ({
currencyDetails,
});
export default connect(mapStateToProps, null)(CurrencyConverter);

第一步是分配'value'作为下拉菜单的一部分。项目:

<Dropdown.Item
key={Math.random()}
text={item.currencyName}
image={item.flag}
value={item.value}
style={{ height: "70px", fontSize: "17px" }}
onClick={(event, item) => {
console.log(item);
}}
/>

然后你可以从onClick事件传递的item中获取'value'。

onClick={(event, item) => console.log(item.value)}

只要你在最初的下拉菜单中设置了"value"而不是"text",这也会让下拉菜单柄在不活动时显示正确的值

下面是代码的一个稍微简化的版本:

const currencyDetails = [
{currencyName: 'United States Dollars', value: 'USD'},
{currencyName: 'Canadian Dollars', value: 'CDN'}
]
const initialData = {currency: 'USD'}
const CurrencyConverter = () => {
const handleSelection = (e, value) => {
console.log(value)
alert(`"I Chose the value ${value.value}`)
}
return (
<div className="currency-form">
<Dropdown
inline
value={initialData.currency}
>
<Dropdown.Menu
>
{currencyDetails.map((item) => (
<Dropdown.Item
key={item.currencyName}
value={item.value}
text={item.currencyName}
style={{ height: "70px", fontSize: "17px" }}
onClick={handleSelection}
/>
))}
</Dropdown.Menu>
</Dropdown>
</div>
)
}

阅读更多请查看文档:
https://react.semantic-ui.com/modules/dropdown/#usage-controlled

最新更新