如何为API映射生成的下拉选框添加默认不可选选项
解决方案
直接在<select>标签内的最顶部添加默认不可选选项,同时移除标签上无效的option属性即可,修改后的代码如下:
<select className="appearance-none text-center p-4 w-full text-md font-semibold leading-none bg-dark-purple text-white border-light-purple rounded outline-none" name="field-name" placeholder="Select another year" id="selectYears"> {/* 默认不可选选项 */} <option disabled selected value="">--选择年份--</option> {remainingYears.map((data, index) => { if (latestYear - data.year > 29) { return ( <option key={data.year} value={data.year}> {data.year} </option> ); } })} </select>
关键修改说明:
- 默认选项通过
disabled设置为不可点击状态,selected让页面加载时自动选中该选项,value设为空字符串避免提交无效值 - 移除
<select>标签上多余的option属性,该属性不属于<select>的合法属性,会造成无效标记
内容的提问来源于stack exchange,提问作者David Verduzco
相关产品推荐
相关产品推荐

