|
|
|
|
|
by matthewmacleod
4000 days ago
|
|
Personally, I use refs a lot to bubble events down the component hierarchy. For example, when the browser window loses focus and gains it again, some sub sub component of the root component might want to do set some local state. Whatever, display a "welcome back!" message or something Isn't that a bit of an antipattern? It seems that sending events down the hierarchy is something that React goes out of its way to make awkward, and on purpose. In the case you've given, I'm not clear why you wouldn't just bind to the window's focus and blur events from within componentWillMount, anyway. |
|
Another use case that I came across was where we wanted a search dropdown to open in the header when a user clicked somewhere in the middle of the page content. One option would be to make a PageStateStore and add an isSearchDropdownVisible to it, but I don't like doing flux that way because I don't want UI details to be part of my model later.
I think having isVisible in the SearchDropdown state is much more elegant, but that poses the slight problem of how to change that state from the other side of the page. We did that by having the item in the page have an onWantToSearch event, which the page had a handler for that invoked this.refs.header.showSearch(), which in turn invoked this.refs.searchDropdown.setVisible(true), which did a simple this.setState({isVisible: true}).
So, in general, the event first bubbles all up the tree (through custom react onSomething, onSomethingElse props), and then bubbles down the tree (through method calls on refs). This exposes a really elegant design, because it made the Header component be "a thing that allows searching" (because it has a showSearch() method), and the page item an "a thing that allows a user to initiate a search action" (because it has a onWantToSearch event). The available methods and onSomething props of all components perfectly matched the possible behaviors of the components, and no behaviour is "hidden" inside a singleton mesh of flux stores.