【发布时间】:2016-09-15 00:26:06
【问题描述】:
我在一个项目中使用带有 React 的 Typescript。 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 方法中,我只尝试为一个属性设置状态,{ editorState: EditorState;} 类型中缺少属性todos 和属性hungry。换句话说,我需要在onChange 函数中设置所有三个属性的状态才能使代码编译。为了让它编译,我需要做
onChange(editorState: EditorState){
this.setState({
todos: [],
hungry: false,
editorState: editorState
});
}
但此时没有理由在代码中设置todos 和hungry 属性。在 typescript/react 中仅对一个属性调用 setState 的正确方法是什么?
【问题讨论】:
标签: reactjs typescript