I'm using Typescript with React for a project. The Main component gets passed state with this interface.
interface MainState {
todos: Todo[];
hungry: Boolean;
editorState: EditorState; //this is from Facebook's draft js
}
However, the code below (only an excerpt) won't compile.
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
});
}
}
The compiler complains that, in the onChange
method where I am only trying to setState for one property, the property todos
and the property hungry
is missing in type { editorState: EditorState;}
. In other words, I need to set the state of all three properties in the onChange
function to make the code compile. For it to compile, I need to do
onChange(editorState: EditorState){
this.setState({
todos: [],
hungry: false,
editorState: editorState
});
}
but there's no reason to set the todos
and the hungry
property at this point in the code. What is the proper way to call setState on only one property in typescript/react?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…