这在 React 组件中

This in React component

好的,我在理解这个概念时遇到了一些麻烦。帮帮我!

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>  
      }; 

我在做什么:

1.Send array to parent(Menu) props,array 包括菜单组件的一些参数和child(Canvas).

的道具
let menu_props=[
            props,
            width,
            height
        ];  

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

2.Attach Canvas props 从这个数组到 Menu

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

3.Call setState 来自 parent(菜单)

结果

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

问题:我知道出于某种原因我的 canvas 组件开始引用 parent 组件的这个,我不明白为什么会这样.我如何封装每个单独组件的范围,以便他可以引用他自己的这个。谢谢!

我认为您无法访问 parent 的 this。但是,我有点惊讶为什么你使用 children[<index>] 而不是简单地传递 menu_props 作为道具:

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

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

然后你将拥有:

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

在你的 Canvas 中。总的来说,我看不到在 React 组件中使用 this 有多大价值,因为您可以在每个 class 方法中访问 this.props。所以如果你需要一些东西

const { <something> } = this.props;