首页 > 解决方案 > 如何获取下拉 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
    }

任何帮助将不胜感激,非常感谢!

标签: reactjsspring-boot

解决方案


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>
);

推荐阅读