我在一个项目中使用 Typescript 和 React。Main 组件通过此接口获取传递状态。
interface MainState {
todos: Todo[];
hungry: Boolean;
editorState: EditorState; //this is from Facebook's draft js
}
但是,下面的代码(仅摘录)将无法编译。
class Main extends React.Component<MainProps, MainState> {
constructor(props) {
super(props);
this.state = { todos: [], hungry: true, editorState: EditorState.createEmpty() };
}
onChange(editorState: EditorState) {
this.setState({
editorState: editorState
});
}
}
编译器抱怨说,在onChange
我只尝试为一个属性设置状态的方法中,属性todos
和属性hungry
在 type 中丢失{ editorState: EditorState;}
。换句话说,我需要在onChange
函数中设置所有三个属性的状态才能使代码编译。为了编译,我需要做
onChange(editorState: EditorState){
this.setState({
todos: [],
hungry: false,
editorState: editorState
});
}
但此时没有理由在代码中设置todos
和hungry
属性。在typescript/react中仅对一个属性调用 setState 的正确方法是什么?