简体   繁体   中英

React.js + Flux — Passing callback as a prop in view

The official React.js tutorial has an interesting practice of passing a callback as a prop to a child component. In their example, they have a parent component named CommentBox and a child component named CommentForm . The parent ( CommentBox ) passes a callback method handleCommentSubmit to the child ( CommentForm ). When the form is submitted, the child component fires the callback to notify the parent that the form has been submitted.

However, this React tutorial is not a tutorial on the Flux architecture . From my limited flux perspective, my first instinct is that the child view should call an action, which (via the global dispatch system) updates a store. The updated store would then trigger an update of any component that cared to know, including the parent component in question, the CommentBox .

In other words, the parent component would not care, nor would it want to know about what its child, the CommentForm is doing, or when the form is submitted. Instead, it would rerender when the store is updated. This means that anything that triggers a store update would cause the CommentBox to be updated (this is a good thing in my opinion; what if there were multiple ways of submitting a comment?)

This brings me to my main question: Are there ever situations in the Flux architecture in which it would be appropriate to pass a callback method to a child component, or is this in general an anti-pattern?


Note: Flux + React.js - Callback in actions is good or bad? is not the same question -- I'm asking about callbacks in views, not in the actions.

If you have a pure UI component, like a fancy button, it makes sense to enable callbacks in the UI; actions should only be used for triggering application changes:

<MyFancyButton onClick={this.handleClick}/>

Obviously, MyFancyButton doesn't have enough information to know what the click should do; it'd be up to the parent view that uses it to decide which actions to dispatch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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