javascript - 如何在单击提交时或第一次加载时设置默认选定值 - React Hook
问题描述
这是我的类别状态
const [category, setCategory] = useState('');
这是表单元素:
<select onChange={e => setCategory(e.target.value)}>
<Options options={categoryList} value={category}/>
</select>
在更改值时,我正在选择类别
const handleBusinessInfoSubmit = (e) => {
try{
e.preventDefault();
console.log("category selected is " +category);
}
catch{
console.log("something went wrong!");
}
}
当用户不更改值并点击提交时,如何设置类别状态?
作为参考,这里是类别列表,稍后将在键值对中以动态形式出现
const categoryList = [
{
id: 1,
value: 'Public Services'
}, {
id: 2,
value: 'Automotive'
}
];
// generate select dropdown option list dynamically
function Options({ options }) {
return (
options.map(option =>
<option key={option.id} value={option.value}>
{option.value}
</option>)
);
}
解决方案
可能我会将默认初始值添加到useState
as 而不是''
:
const [category, setCategory] = useState(categoryList[0]);
或者,如果数据是动态来的,那么setCategory()
使用 API 结果中的值调用您希望拥有的默认值。
我希望这有帮助!
推荐阅读
- javascript - 将具有重复键的键值数组转换为具有唯一键和值数组属性的对象数组
- javascript - 使用 jquery 的响应式菜单
- python - 如何通过用户输入在 Python 3 中创建无限嵌套字典
- php - php中的Stackoverflow编辑器url替换
- javafx - 关于为什么在尝试抓取窗口大小时对象不会画圆的困惑
- java - 无法为 Spring jersey 应用程序创建自定义错误
- json - 通过 react-native 中的键值迭代 JSON 数组
- android - 将设备壁纸设置为渐变背景(Android Studio)
- javascript - 使用 JavaScript 在表格中创建新行,innerHTML 设置输入变量,但用户输入的值在提交时不会发布
- html - Golang HTML Web Apps 中没有这样的模板“xxx”