我想从下拉列表中获取下拉列表的标签(例如:库存部分,非库存部分 ..) 下拉列表的代码为
<select value={'ItemType'} onChange={this.handleChange} style={{'width':'448px'}}>
<option value='0'>Select An Item Type</option>
<option value='1'>**Inventory Part**</option>
<option value='2'>**Non-Inventory Part**</option>
<option value='3'>Other Change</option>
<option value='4'>Subtotal</option>
<option value='5'>Group</option>
<option value='6'>Discount</option>
<option value='7'>Payment</option>
<option value='8'>Sales Tax Item</option>
<option value='9'>Sales Tax Group</option>
</select>
handleChange函数和构造函数如下:
constructor(props){
super(props);
this.state={type:''}
}
handleChange = (e) => {
this.setState({type:e.target.value});
};
如何修改 handleChange ,以便获得选项的标签?
答案 0 :(得分:3)
您可以使用此
var index = e.nativeEvent.target.selectedIndex;
var text =e.nativeEvent.target[index].text;
console.log(text);
您的手柄更改方法
handleChange = (e) => {
var index = e.nativeEvent.target.selectedIndex;
var text =e.nativeEvent.target[index].text;
console.log(text);
this.setState({type:e.target.value});
};
答案 1 :(得分:2)
添加保存标签的新状态“标签”
constructor(props){
super(props);
this.state={type:'', label: ''}
}
handleChange = (e) => {
let index = e.nativeEvent.target.selectedIndex;
let label = e.nativeEvent.target[index].text;
let value = e.target.value;
this.setState({ type: value, label: label});
}
答案 2 :(得分:1)
最好的方法是根据需要的数据生成下拉列表的值:
const itemTypes = {
"0": "Select An Item Type",
"1": "Inventory Part",
"2": "Non-Inventory Part",
"3": "Other Change",
"4": "Subtotal",
"5": "Group",
"6": "Discount",
"7": "Payment",
"8": "Sales Tax Item",
"9": "Sales Tax Group",
};
class Component extends React.Component {
// ...
handleChange = e => {
const itemTypeId = e.target.value;
const itemTypeText = itemTypes[itemTypeId];
console.log(itemTypeText); // Do what you need to with the value here
this.setState({ type: itemTypeId });
};
// ...
render() {
return (
<select
value="ItemType"
onChange={this.handleChange}
style={{ width: "448px" }}
>
{Object.keys(itemTypes).map(typeId => (
<option value={typeId}>{itemTypes[typeId]}</option>
))}
</select>
);
}
}
答案 3 :(得分:0)
访问下面的链接进行多选下拉列表
答案 4 :(得分:0)
如果您只想获取所选选项的标签,那将非常简单。
<option value="Inventory Part">**Inventory Part**</option>
和您的手柄更改将保持不变。
let index = e.nativeEvent.target.selectedIndex;
let label = e.nativeEvent.target[index].text;
答案 5 :(得分:0)
您可以使用事件nativeEvent目标对象中的innerText
属性,而无需使用状态:
handleChange = (e) => {
const { innerText } = e.nativeEvent.target
// innerText will have the label of the selected option
};