reactjs - 如何获取下拉 React 的特定 ID?
问题描述
我是 React 和 Spring Boot 的初学者,我正在尝试寻找一种从选定下拉列表中获取 id 值并将其传递给对象的方法。我有一个从 Spring Boot 的 Category 类中获取数据的下拉列表
async componentDidMount() {
const response = await fetch('/api/categories'); // Fetch data from GET endpoint in Spring Boot
const body = await response.json();
this.setState({categories: body});
}
在渲染()中:
let optionList =
categories.map (category =>
<option value={category.id} key={category.id}>{category.categoryName}</option>
)
return (
// Other codes
<FormGroup>
<select>{optionList}</select>
</FormGroup>
);
我试图在这里传递 category.id 以便创建的每个新对象都可以具有与从下拉列表中选择的类别相对应的类别
itemBlueprint = {
description: '',
category: {id: 1, categoryName: ''} // Currently hardcoded category id
}
任何帮助将不胜感激,非常感谢!
解决方案
select 附带处理程序onChange
,它为回调处理程序提供事件参数。
const [selectedCategory, setSelectedCategory] = useState(null)
const selectOnChange = (event) => {
setSelectedCategory(event.target.value)
}
let optionList = categories.map(category =>
<option value={category.id} key={category.id}>{category.categoryName}</option>
)
return (
// Other codes
<FormGroup>
<select onChange={selectOnChange}>{optionList}</select>
</FormGroup>
);
推荐阅读
- java - @RequestParam not mapping entire string
- python - require() 给出一个参考错误 - Uncaught ReferenceError
- c++ - 为什么 GCC/Clang 不解析具有相同名称的覆盖方法?
- node.js - 不执行 multer 库的测试
- sql - 按表分组,然后将另一个表计数添加到第一个表分组计数中
- java - 如何模拟 SpyBean 的各个方法?
- codeigniter - 如何向codeigniter添加新字段?
- sql - 从 Oracle 中的逗号分隔字符串中转义单引号
- javascript - 输入类型电子邮件仍然允许通过
- python - pyspark:数据框在另一个数据框的列中按ID选择行