Anatoly Strashkevich
Anatoly Strashkevich

Reputation: 1914

This in React component

Ok, i have some troubles understanding the concept. Help me out!

Parent component:Menu

export class Menu extends React.Component<any,any>{
...whole bunch of stuff
 .
 .
 .some nested components in render
    render(){     
       return <MuiThemeProvider muiTheme={muiTheme}>  
        <ReactGridLayout {...some_props}>
            <div key={'canvas'}>               


 <Canvas {...this.canvas}/>


             </div>
        </ReactGridLayout>   
        </MuiThemeProvider>   
   }   

Child component:Canvas

export class Canvas extends React.Component<CanvasProps,CanvasState>{
...whole bunch of stuff
     .
     .
render(){        
        //return this.props.decorate(this.createCanvas());
        return <canvas
                width={this.width}
                height={this.height}  
                onClick={this.lock(this.setSelected)} 
                onWheel={this.lock(this.zoom)}   
                onMouseMove={this.lock(this.rotate)}
                >{this.props.title}
                </canvas>  
      }; 

What i'm doing:

1.Send array to parent(Menu) props, array include some parameters for menu component and props for child(Canvas).

let menu_props=[
            props,
            width,
            height
        ];  

        ReactDOM.render( 
            <Menu>            
                {...menu_props}
            </Menu>,  
            document.getElementById('canvas')
        ); 

2.Attach Canvas props from this array to this in Menu

this.canvas=this.props.children[0];   
this.width=this.props.children[1]; 
this.height=this.props.children[2];

3.Call setState from parent(Menu)

Result

TypeError: this.context.clearRect is not a function at Canvas.componentDidUpdate (canvas.js:63996)

Question: I understand that for some reason my canvas component start to referring to this of parent component, i cant understand why is this happening. How i can encapsulate scope of each individual component so he could refer to his own this. Thank you!

Upvotes: 0

Views: 557

Answers (1)

Krasimir
Krasimir

Reputation: 13529

I don't think that you have access to parent's this. However, I'm a little bit surprised why you are using children[<index>] instead of simply pass menu_props as props:

let menu_props = {
  canvas: props,
  width,
  height
};

ReactDOM.render( 
  <Menu { ...menu_props } />,
  document.getElementById('canvas')
);

And then you'll have:

const { canvas, width, height } = this.props;

in your Canvas. In general I don't see much of a value using this in React components because you have access to this.props in every class method. So if you need something just

const { <something> } = this.props;

Upvotes: 1

Related Questions