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 });
これは活字体またはリアクトのようなシステムを入力のいくつかのフォームを使用する利点の教科書の一例です。このようなことを捕まえ、正しい、慣用的なリアクションコードを書くのを助けます。 – GregL