javascript - In React can properties of grandparents be accessed by a grandchild without the parent passing it down? -
i working on first react project , came issue passing data between components. using libraries calendar widget in order style different days depending on selected item in list.
https://github.com/vazco/meteor-universe-react-widgets
i have 4 interacting components within tree in structure:
-----a----- | | c b | | d
i storing data of selected item in list (component b) top level component (component a). component want pass data component d. want create state , pass value c , on d. unfortunately, c calendar component library cant manipulate.
as need object generated selection in b accessed d without being able manipulate c, there way pass values on head of child component?
code snippets:
how component c (calendar) called in a, while passing in component d (daycomponent).
<calendar daycomponent={daycomponent}/>;
the calendar component declaration & import
system.import('{universe:react-widgets}').then(reactwidgets => { calendar = reactwidgets.calendar; });
the day component returns styling calendar days.
daycomponent = react.createclass({ render() { var date = this.props.date , style = { backgroundcolor: date < new date() && '#f57b7b' } return (<div style={style}> {this.props.label} </div>); } })
not props, no. that's not how react works. react send props in top-down direction, parents passing properties children. idea component shouldn't care it's rendered, or what, long props set valid.
that being said, there is facility "punching hole" (so speak) in component tree, allow child component access data higher in tree: context
however, context regarded advanced feature, , only used in specific situations solution isn't viable.
from docs page:
note: context advanced , experimental feature. api change in future releases. applications never need use context. if getting started react, not want use context. using context make code harder understand because makes data flow less clear. similar using global variables pass state through application. if have use context, use sparingly.
the idea in top level component define context properties want make available, , method return context data:
class topcomponent extends component { childcontexttypes: { color: react.proptypes.string }, getchildcontext: function() { return {color: "purple"}; }, .. }
and in child component somewhere down tree, tell component context properties want access to:
class childcomponent extends component { contexttypes: { color: react.proptypes.string }, ... }
and properties accessible via this.context
property (this.context.color
instance).
Comments
Post a Comment