反应扩展组件和打字稿泛型 & setState
react extended component & typescript generics & setState
我有一个用 typescript 编写的 React 组件 PageLayout:
export interface IPageLayoutProps {...}
export interface IPageLayoutActions {...}
export interface IPageLayoutLocalState {...}
export default
class PageLayout<P extends IPageLayoutProps & IPageLayoutActions, S extends Object>
extends React.Component<P, S>
{
render() {
return (...)
}
}
然后我尝试像这样扩展这个组件:
import PageLayout, { IPageLayoutProps, IPageLayoutActions, IPageLayoutLocalState } from './PageLayout'
export interface IPageLayoutSidebarProps {...}
export interface IPageLayoutSidebarActions {...}
interface IPageLayoutSidebarState {sidebarVisible: boolean}
export default
class PageLayoutSidebar<P extends IPageLayoutSidebarProps & IPageLayoutSidebarActions & IPageLayoutProps & IPageLayoutActions, S extends IPageLayoutSidebarState & IPageLayoutLocalState>
extends PageLayout<P, S>
{
render() {
return (...)
}
toggleSidebar(visible:boolean) {
this.setState({
...this.state,
sidebarVisible: visible
})
}
}
问题是我在尝试调用 this.setState 时遇到错误,它告诉我 "spread types may only be created from object types"。任何人都知道状态可能有什么问题以及为什么我不能在其上使用展开运算符?
尝试只使用:
this.setState({sidebarVisible: visible})
我有一个用 typescript 编写的 React 组件 PageLayout:
export interface IPageLayoutProps {...}
export interface IPageLayoutActions {...}
export interface IPageLayoutLocalState {...}
export default
class PageLayout<P extends IPageLayoutProps & IPageLayoutActions, S extends Object>
extends React.Component<P, S>
{
render() {
return (...)
}
}
然后我尝试像这样扩展这个组件:
import PageLayout, { IPageLayoutProps, IPageLayoutActions, IPageLayoutLocalState } from './PageLayout'
export interface IPageLayoutSidebarProps {...}
export interface IPageLayoutSidebarActions {...}
interface IPageLayoutSidebarState {sidebarVisible: boolean}
export default
class PageLayoutSidebar<P extends IPageLayoutSidebarProps & IPageLayoutSidebarActions & IPageLayoutProps & IPageLayoutActions, S extends IPageLayoutSidebarState & IPageLayoutLocalState>
extends PageLayout<P, S>
{
render() {
return (...)
}
toggleSidebar(visible:boolean) {
this.setState({
...this.state,
sidebarVisible: visible
})
}
}
问题是我在尝试调用 this.setState 时遇到错误,它告诉我 "spread types may only be created from object types"。任何人都知道状态可能有什么问题以及为什么我不能在其上使用展开运算符?
尝试只使用:
this.setState({sidebarVisible: visible})