對於由React和TypeScript創建的這樣一個小組件。如何使用React TypeScript 2.0更改狀態?
interface Props {
}
interface State {
isOpen: boolean;
}
class App extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
isOpen: false
};
}
private someHandler() {
// I just want to turn on the flag. but compiler error occurs.
this.state.isOpen = true;
this.setState(this.state);
}
}
當我試圖升級TypeScript 1.8到2.0,然後我得到像下面的編譯器錯誤。
error TS2540: Cannot assign to 'isOpen' because it is a constant or a read-only property.
我想也許是由這個變化引起的。
,所以我只是想打開標誌。
我該怎麼辦?有誰知道解決方法?
謝謝。
更新
快速解決方法就像下面這樣做。
this.setState({ isOpen: true });
這是使用某種形式的像打字稿或輸入做出反應體系的好處典型例子。它捕獲這樣的事情,並幫助您編寫正確的,慣用的React代碼。 – GregL