React.js component creating parent child relations and iteration

I am trying to have a component that can find parent / child components of the same type. These components must also be “reproducible” programmatically.

In this way:

<MyComponent id="1> <div> <MyComponent id="2"> <div> <MyComponent id="3"></MyComponent> </div> <div> <MyComponent id="4"></MyComponent> </div> </MyComponent> </div> </MyComponent> 

Basically what I need is a way to cross the MyComponents tree (the traversal is logically controlled).

I can pass control / parameters to the parent component or pass the control of the parent component / parameters to the child components in a predetermined order (based on data). I have two ways to do this, both include preprocessors. One of them is a preprocessor that generates a new component for each MyComponent found with some template. Sort of:

 var MyComponent_1 = React.createClass({ initialState: function(){ return {currentObject: 0} }, parentCallback: function(x){ /* traversal logic */ }, render: function(){ var nodes=[]; for(var i=0;i<RepeatParam;i++) nodes.push((<div><MyComponent_2 parent={parent}></MyComponent_2></div>)); return nodes; } }); var MyComponent_2 /** just like the above */ 

Another method was to add function closures, something like this:

 var $parent=0, parent=0; <div> (function(){parent=$parent;$parent=1; return (<MyComponent parent={parent}> <div> (function(){parent=$parent;$parent=2; <MyComponent parent={parent}></MyComponent> })() </div></MyComponent>}))()</div> 

Another method is to use global variables and paste them into createClass.

All of these methods seem to be wrong, and as if I had a very big misunderstanding of how React should work. Is there a more elegant way to be able to cross the component tree, and what is the anti-pattern that I commit; how should i do this?

0
source share
1 answer

Now it can be done using the "context" api

 export class Hierarchy { contextTypes: { level: React.PropTypes.number } childContextTypes: { level: React.PropTypes.number } getChildContext() { return { level: this.context.level + 1 }; } render() { return <div>{this.context.level}{this.children}</div>; } } 

The combination of higher order components, contexts, and flow facilitates implementation.

0
source

Source: https://habr.com/ru/post/977142/


All Articles