我正在使用typescript@2.6.1并做出反应和反应@ 15.6.2。
我似乎无法调试此问题:
未捕获的TypeError:无法在Menu.handleClick中读取未定义的属性“setState”。
这是this.setState( (prevState) => {
import * as React from "react";
import * as ReactDOM from 'react-dom';
import Monaco from './Monaco';
import shiftOverlayButtons from '../common/shiftOverlayButtons';
export interface Props {
}
export interface State {
isOpen: boolean;
}
export default class Menu extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
}
public state: State = {
isOpen: false
};
public render() {
return <button id="overlay-btn" className="menu-btn" onClick={this.handleClick}></button>
}
public handleClick(): void {
this.setState( (prevState) => {
if(prevState.isOpen === false){
this.openMenu();
return {
isOpen: true
};
}
else {
this.closeMenu();
return {
isOpen: false
}
}
});
}
private openMenu(): void {
shiftOverlayButtons(true);
ReactDOM.render(<Monaco/>, document.getElementById("overlay"));
}
private closeMenu(): void {
shiftOverlayButtons(false);
//ReactDOM.unmountComponentAtNode(document.getElementById("overlay"));
}
}
ReactDOM.render(<Menu/>, document.body);
PS:当我this.handleClick.bind(this)
时,我收到另一个错误:GET file:///Users/kalpa/Desktop/monaco-sample/vs/loader.js net :: ERR_FILE_NOT_FOUND ...我正在使用webpack @ 3.8.1
答案 0 :(得分:1)
首选使用箭头功能处理程序。变化
public handleClick(): void {
到
public handleClick = (): void => {
箭头功能:https://basarat.gitbooks.io/typescript/docs/arrow-functions.html
答案 1 :(得分:0)
您在处理单击时缺少绑定。所以来自
onClick={this.handleClick}
到
onClick={this.handleClick.bind(this)}
重新格式代码:
handleClick(event) {
this.setState({isOpen: !isOpen}).then(()=>{
if(!this.state.isOpen){
//do something when false
} else {
// do something when true
}}}