我正在为一个项目使用带有React的Typescript.主组件通过此接口获得传递状态.
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
});
}
}
编译器抱怨说,在我只try 为一个属性设置state的onChange
方法中,{ editorState: EditorState;}
类型中缺少属性todos
和属性hungry
.换句话说,我需要设置onChange
函数中所有三个属性的状态,以使代码能够编译.要编译它,我需要
onChange(editorState: EditorState){
this.setState({
todos: [],
hungry: false,
editorState: editorState
});
}
但是没有理由在代码中的这一点上设置todos
和hungry
属性.在typescript/react中,只对一个属性调用setState的正确方法是什么?