React.Js 查找数组中的哪个元素被用户选择

发布于 2025-01-18 17:08:30 字数 310 浏览 3 评论 0原文

基本上我有一个组件,它是用户已加入的房间列表。在此组件之上有一个搜索部分,除了搜索输入之外,还有一些有关搜索的选项,例如按“房间名称”搜索、按“组织名称”搜索等。我将此选项保留在选项 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暗喜 2025-01-25 17:08:30

您需要使用反应状态挂钩来实现相同的目的。
每当选择其中之一时,请使用所选名称或 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/

时光是把杀猪刀 2025-01-25 17:08:30

我将此选项与选项 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文