反应组件错误 Cannot read 属性 of undefined
react component error Cannot read property of undefined
我是 React 的新手,我创建了这样的组件;
export default class CartoviewDrawer extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
}
_handleToggle() {
let open = this.state.open;
this.setState({open: !open})
}
render() {
return (
<div>
{/*<RaisedButton*/}
{/*label="Toggle Drawer"*/}
{/*onTouchTap={this.handleToggle}*/}
{/*/>*/}
<IconButton tooltip="Toggle Drawer"
onTouchTap={this._handleToggle}
>
<i className="material-icons">list</i>
</IconButton>
<IconButton iconClassName="muidocs-icon-custom-github"/>
<Drawer open={this.state.open}>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item 2</MenuItem>
</Drawer>
</div>
);
}
}
在另一个文件中,我通过 ;
导入了这个组件
import CartoviewDrawer from './cartoview_drawer'
然后我使用这个组件:
React.createElement(AppBar,toolbarOptions,React.createElement(CartoviewDrawer))
但是当我点击浏览器控制台中的图标错误并且没有出现抽屉时。
错误:
Uncaught TypeError: Cannot read property 'open' of undefined
您缺少与 'this' 的绑定
将 onTouchTap 调用更改为此:
onTouchTap={this._handleToggle.bind(this)}
在组件构造函数中添加绑定:
constructor(props) {
super(props);
...
this._handleToggle= this._handleToggle.bind(this);
}
我是 React 的新手,我创建了这样的组件;
export default class CartoviewDrawer extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
}
_handleToggle() {
let open = this.state.open;
this.setState({open: !open})
}
render() {
return (
<div>
{/*<RaisedButton*/}
{/*label="Toggle Drawer"*/}
{/*onTouchTap={this.handleToggle}*/}
{/*/>*/}
<IconButton tooltip="Toggle Drawer"
onTouchTap={this._handleToggle}
>
<i className="material-icons">list</i>
</IconButton>
<IconButton iconClassName="muidocs-icon-custom-github"/>
<Drawer open={this.state.open}>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item 2</MenuItem>
</Drawer>
</div>
);
}
}
在另一个文件中,我通过 ;
导入了这个组件import CartoviewDrawer from './cartoview_drawer'
然后我使用这个组件:
React.createElement(AppBar,toolbarOptions,React.createElement(CartoviewDrawer))
但是当我点击浏览器控制台中的图标错误并且没有出现抽屉时。 错误:
Uncaught TypeError: Cannot read property 'open' of undefined
您缺少与 'this' 的绑定 将 onTouchTap 调用更改为此:
onTouchTap={this._handleToggle.bind(this)}
在组件构造函数中添加绑定:
constructor(props) {
super(props);
...
this._handleToggle= this._handleToggle.bind(this);
}