javascript - React 组件中的 this

标签 javascript reactjs typescript react-dom

好吧,我在理解这个概念时遇到了一些困难。帮帮我吧!

父组件:菜单

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

子组件: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.将数组发送到(菜单) Prop ,数组包含菜单组件的一些参数和( Canvas )。

let menu_props=[
            props,
            width,
            height
        ];  

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

2.将此数组中的 Canvas 属性附加到 Menu 中的此属性

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

3.从父级调用setState(菜单)

结果

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

问题:我知道由于某种原因我的 Canvas 组件开始引用父组件的 this,我无法理解为什么会发生这种情况。我如何封装每个单独组件的范围,以便他可以引用他自己的 this.谢谢你!

最佳答案

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

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

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

然后你将拥有:

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

在你的Canvas中。一般来说,我认为使用 this 没有太大值(value)。在 React 组件中,因为您可以访问 this.props在每个类方法中。所以如果你需要一些东西

const { <something> } = this.props;

关于javascript - React 组件中的 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44565511/

相关文章:

javascript - 更改助手 ID

javascript - array 在 typescript,javascript 中转换

reactjs - 如何通过Jenkins从Docker容器中获取构建目录?

javascript - React - 如何从 useState 中的后端 API 获取初始值?

javascript - 同时使用redux和redux工具包

javascript - 是否可以在 Styles.scss 中动态导入 Variables.scss 文件?

javascript - 更新数组时 Redux 状态未更新

javascript - 制作 X 与 Y 的图表

php - Jquery:在没有网络服务器的情况下在本地运行 AJAX

javascript - ng-重复不起作用