简体   繁体   English

React.js:为什么传递回调以将数据更新到拥有的组件

[英]React.js: why pass callbacks for updating data to owned components

I'm doing the React.js tutorial ( http://facebook.github.io/react/docs/tutorial.html ), and don't understand the reasoning behind this line: 我正在做React.js教程( http://facebook.github.io/react/docs/tutorial.html ),并且不了解这行背后的原因:

It makes sense to do all of this logic in CommentBox since CommentBox owns the state that represents the list of comments. 在CommentBox中执行所有这些逻辑是有意义的,因为CommentBox拥有代表注释列表的状态。

Why doesn't CommentBox just pass the list of comments to CommentForm so it can add the new comment to the list, instead of passing onCommentSubmit callback? 为什么CommentBox不只是将注释列表传递给CommentForm,以便它可以将新注释添加到列表中,而不是传递onCommentSubmit回调?

In general, this inversion of control allows you to centralize stateful data and the manipulation of that data in the component that's "responsible" for keeping track of it and gives you less reason to change components. 通常,控制权的反转使您可以集中状态数据,并在“负责任”的组件中对这些数据进行操作以跟踪它,并减少更改组件的理由。 For example, if the list of comments one day turns into a map of comments, or an immutable data structure of comments, you shouldn't have to change CommentForm , only CommentBox . 例如,如果某天的评论列表变成了评论图或评论的不可变数据结构,则不必更改CommentForm ,而只需更改CommentBox

This also allows you to build more reusable components. 这也使您可以构建更多可重用的组件。 For example, it's not a stretch to imagine a scenario where you'd want to be able to edit a comment. 例如,想像一下您想要能够编辑评论的场景并不是一件容易的事。 By passing a change handler into CommentForm , it would be possible to reuse this component for editing as well as creating comments, but this is only possible if you don't make assumptions inside the form as to what should happen when it submits. 通过将更改处理程序传递到CommentForm ,可以重用此组件进行编辑和创建注释,但这只有在您不对表单内部提交时应做的假设的情况下才有可能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM