我可以访问数组中子组件的状态值吗?

发布于 2025-01-18 08:11:33 字数 654 浏览 0 评论 0原文

我对 React 很陌生,正在为学校项目学习它。我尝试寻找这个答案,认为这是一个相当简单的解决方案,但我很难找到与我的场景相匹配的结果。

本质上,我希望拥有一个特定组件(例如 Child)的数组,每个组件在其状态下保存一个值(例如 { value: 2 } )。我希望迭代该数组,访问每个组件的 state.value,并从中计算总数。

我最初的想法是将数组保持在父级的状态,然后迭代数组,执行如下操作:

this.state.children.map(child => (
    child.state.value
))

但是,结果返回为“值”未定义,导致我相信我无法访问另一个组件的状态这边走。

我还研究了使用 refs,如以下文章所述: https://www.geeksforgeeks.org/how-to -access-childs-state-in-react/

但是,似乎这只允许我创建对单个子组件的引用,这意味着我需要为数组中的每个子组件提供一个新的引用。

任何关于我能做什么的建议或示例代码(越基本越好)将不胜感激!

I'm very new to React, in the process of learning it for a school project. I've tried searching for this answer thinking it'd be a fairly simple solution, but I'm having trouble finding a result that matches my scenario.

Essentially I'm looking to have an array of a specific component (e.g. Child), each holding a value in their state (e.g. { value: 2 } ). I'm looking to iterate through the array, accessing each component's state.value, and calculate a total from it.

My initial thought was to hold the array in the parent's state, and then iterate through the array doing something like this:

this.state.children.map(child => (
    child.state.value
))

However, the result is coming back as 'value' being undefined, leading me to believe I can't access another component's state this way.

I also looked into using refs, as described in the following article:
https://www.geeksforgeeks.org/how-to-access-childs-state-in-react/

However, it seems as though that only lets me create a reference to a single child, meaning I would need a new reference for every child component in the array.

Any advice or sample code of what I could do (the more basic the better) would be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文