我正在将一个带有React的Typescript用于一个项目.Main组件通过此接口获得传递状态.
interface MainState {
todos: Todo[];
hungry: Boolean;
editorState: EditorState; //this is from Facebook's draft js
}
Run Code Online (Sandbox Code Playgroud)
但是,下面的代码(仅限摘录)将无法编译.
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
});
}
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨说,在onChange我只尝试为一个属性设置setState 的方法中,属性todos和属性hungry在类型中缺失{ editorState: EditorState;}.换句话说,我需要在onChange函数中设置所有三个属性的状态以使代码编译.为了编译,我需要做
onChange(editorState: EditorState){
this.setState({
todos: [],
hungry: false,
editorState: editorState
});
}
Run Code Online (Sandbox Code Playgroud)
但是没有理由在代码中设置todos此hungry属性.在typescript/react中只调用一个属性的正确方法是什么?