react 组件错误无法读取未定义的属性
2016-12-28
2740
我是 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
2个回答
在组件的构造函数中添加绑定:
constructor(props) {
super(props);
...
this._handleToggle= this._handleToggle.bind(this);
}
Facundo La Rocca
2016-12-28
您缺少对“this”的绑定 请将 onTouchTap 调用更改为:
onTouchTap={this._handleToggle.bind(this)}
Kinnza
2016-12-28