好吧,我在理解这个概念时遇到了一些困难。帮帮我吧!
父组件:菜单
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/