ReactJS: how to access all child components in parent component?

亡梦爱人 提交于 2020-01-25 12:09:05

问题


Suppose I've got comments list component with comments components. I wanna implement method that will return all comments components. I assigned to each comment component same ref:

<comments>
 <comment ref="myComments" text="abc" />
 <comment ref="myComments" text="efg" />
</comments>

I thought I can access all my components by this.refs.myComments but it doesn't work - it returns only last comment component.

What's the correct way to access all comment components?


回答1:


There is no correct way to do that.

Your view is a representation of your data, so if you want the text for all comments, look at the data.

If you want to update the comments, update the data.

Pulling data out of the view, or manually manipulating the view defeats the purpose of react.



来源:https://stackoverflow.com/questions/26610392/reactjs-how-to-access-all-child-components-in-parent-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!