React下拉框选中值异常:始终返回数组最后一项问题求助
React下拉选择组件始终返回最后一个选项的问题解决
问题原因
你错误地将同一个useRef绑定到了循环生成的每一个<option>元素上。在React循环渲染的过程中,每一次迭代都会覆盖这个ref的指向,最终SelectRef.current只会指向数组的最后一个<option>,所以无论你选择哪个选项,打印的结果都是最后一个元素的name值。
解决方案
方案1:将ref绑定到<select>元素上(非受控组件方式)
直接把ref挂载到父级的<select>标签上,这样通过ref就能直接获取到下拉框当前选中的值:
import loading from "../loading.mp4"; import { Form_Types } from "../components/Form_types"; import { useRef } from "react"; function CreatingDocument() { const SelectRef = useRef(null); const handlerSubmit = (e) => { e.preventDefault(); console.log(SelectRef.current.value); // 现在能正确获取选中的选项值 }; return ( <> <section dir="rtl" id="dashboard"> <form onSubmit={handlerSubmit}> <label htmlFor="Form_Types">Select a vehicle type</label> {/* 把ref移到select标签上 */} <select name="Form_Types" id="Form_Types" ref={SelectRef}> {Form_Types.map((item) => { return ( <option key={item.id} value={item.name}> {item.name} </option> ); })} </select> <button className="btn-dark">Create</button> </form> </section> <video muted loop autoPlay> <source src={loading} type="video/mp4" /> </video> </> ); } export default CreatingDocument;
方案2:使用受控组件(React推荐方式)
通过useState来管理下拉框的选中状态,这是React中处理表单输入更符合设计理念的方式:
import loading from "../loading.mp4"; import { Form_Types } from "../components/Form_types"; import { useState } from "react"; function CreatingDocument() { const [selectedType, setSelectedType] = useState(""); const handlerSubmit = (e) => { e.preventDefault(); console.log(selectedType); // 直接获取状态中的选中值 }; return ( <> <section dir="rtl" id="dashboard"> <form onSubmit={handlerSubmit}> <label htmlFor="Form_Types">Select a vehicle type</label> <select name="Form_Types" id="Form_Types" value={selectedType} onChange={(e) => setSelectedType(e.target.value)} > {Form_Types.map((item) => { return ( <option key={item.id} value={item.name}> {item.name} </option> ); })} </select> <button className="btn-dark">Create</button> </form> </section> <video muted loop autoPlay> <source src={loading} type="video/mp4" /> </video> </> ); } export default CreatingDocument;
内容的提问来源于stack exchange,提问作者Daniel Barda
相关产品推荐
相关产品推荐

