4 回答

TA貢獻1828條經驗 獲得超4個贊
我認為你應該使用值而不是 ID。但如果你非常需要所選選項的 ID 那么你可以嘗試這個-
?handleChange = (event) => {
? ? ? const index = event.target.selectedIndex;
? ? ? const optionElement = event.target.childNodes[index];
? ? ? const optionElementId = optionElement.getAttribute('id');
? ? ? console.log(optionElementId);
? }
選擇列表是-
<select onChange={this.handleChange}>
? ? <option id="1">Travel</option>
? ? <option id="2">Autoloan</option>
</select>

TA貢獻1891條經驗 獲得超3個贊
HTMLSelectElement
元素有selectedIndex
屬性。使用它和孩子列表,您可以獲得孩子的屬性:
<select id="category" onChange={this.selectChanged}>
? ? <option id="1">Travel</option>
? ? <option id="2">Auto Loan</option>
</select>
selectChanged(event){
? ? const select = event.target;
? ? const id = select.children[select.selectedIndex].id;
? ? //now you can store the id's value to state or somewhere else
}
如果您需要進入id表單提交處理程序,您必須通過 id 查找select,然后執行相同的操作:
onSubmit(event) {
? ? const form = event.target;
? ? const select = form.elements.namedItem('category');
? ? const id = select.children[select.selectedIndex].id;
}

TA貢獻1810條經驗 獲得超4個贊
您可以使用來完成此操作value,例如創建此狀態和函數
const [category, setCategory] = useState("1");
const handleChange = (e) => { setCategory(e.target.value) }
那么你可以這樣做
<select value={category} onChange={this.handleChange}>
<option value="1">Travel</option>
<option value="2">Autoloan</option>
</select>

TA貢獻1812條經驗 獲得超5個贊
根據reactjs.org https://reactjs.org/docs/forms.html#the-select-tag, 該<select>
元素在react中與HTML略有不同。在 HTML 中,<select>
創建一個下拉列表。例如,此 HTML 創建一個口味下拉列表:
<select>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option selected value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
請注意,由于選定的屬性,椰子選項最初被選中。React 不使用這個選定的屬性,而是使用根標簽上的value屬性。這在受控組件中更方便,因為您只需在一處更新它。例如:select
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
- 4 回答
- 0 關注
- 214 瀏覽
添加回答
舉報