React.Js 查找数组中的哪个元素被用户选择
基本上我有一个组件,它是用户已加入的房间列表。在此组件之上有一个搜索部分,除了搜索输入之外,还有一些有关搜索的选项,例如按“房间名称”搜索、按“组织名称”搜索等。我将此选项保留在选项 id 旁边的数组。然后我映射该数组以显示所有选项。 现在我可以显示这些选项,但我无法找到一种方法来知道用户选择了哪些选项。用户只需选择一个选项,然后该选项就会突出显示
这是组件
这是我的代码
Basically I have a component that is a list of rooms that a user has joined. On top of this component there is a search section, and aside of the search input there are some options about the search, like search by "Room Name" , search by "Organization name " etc. I keep this options in objects inside of an array alongside the id of the option. Then I map this array to show all the options.
Now I can display those options but I cant find a way to know which of those options the user has selected. The user has to select only one option and then the option is highlighted
This is the component
This is my code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用反应状态挂钩来实现相同的目的。
每当选择其中之一时,请使用所选名称或 ID 或您需要的任何选择器更新状态。
这个示例代码应该有帮助
https://blog.logrocket.com/how-to-build -tab-组件-react/
You need to use react state hook for the same.
Whenever one of them is selected update the state with the selected ones name or id, or any selector you need.
This example code should help
https://blog.logrocket.com/how-to-build-tab-component-react/
我将此选项与选项 id 一起保留在数组内的对象中。然后我映射该数组以显示所有选项。
对于此问题,您必须将对象数组放置在 useState 挂钩中。
文档: https://reactjs.org/docs/hooks-state.html
在您的个人搜索选项对象,添加一个名为 isSelected 的布尔属性,并将默认值设置为 false(尚未选择搜索选项)。
示例对象结构
{ id: 1, optionName: 'Room Name', isSelected: false}
然后,创建一个 onClick 函数,将所选选项的 isSelected 属性设置为 true设置对象数组的新状态。希望这有帮助!好运兄弟
I keep this options in objects inside of an array alongside the id of the option. Then I map this array to show all the options.
For this problem, you have to place your array of objects in a useState hook.
docs: https://reactjs.org/docs/hooks-state.html
In your individual search option objects, add a boolean property named isSelected and set the default values to false (no search options selected yet).
sample object structure
{ id: 1, optionName: 'Room Name', isSelected: false}
then, create an onClick function to set the isSelected property to true of the selected option & to set the new state of the array of objects. Hope this helped! Goodluck brother