4

我正在尝试用withStateHandlersfrom recompose 包装一个无状态功能组件。我发现我能做到这一点的唯一方法是,如果我调整我的证监会的道具以匹配withStateHandlers“泄漏”的某些方面。我做错了什么还是这是recompose类型的缺陷?

我的证监会:

interface IProps {
    className?: string;
    isEditing: boolean;
    toggleEditing: () => void;
}

const MyComponent: React.SFC<IProps> = ({ className, isEditing, toggleEditing }) => (
    <button className={className} onClick={toggleEditing}>{isEditing ? 'stop editing' : 'start editing'}</button>
);

export default MyComponent;

从这里,我想用withStateHandlers

import { withStateHandlers, StateHandlerMap, StateHandler } from 'recompose';
import MyComponent from '../components/myComponent';
interface IProps {
    className?: string;
}

interface IToggleEditingState {
    isEditing: boolean;
}

interface IToggleEditingStateUpdaters extends StateHandlerMap<IToggleEditingState> {
    toggleEditing: StateHandler<IToggleEditingState>
}

const withToggleEditState = withStateHandlers<IToggleEditingState, IToggleEditingStateUpdaters, IProps> (
    { isEditing: false },
    {
        toggleEditing: (state) => () => ({ isEditing: !state.isEditing })
    }
);

const StatefulMyComponent = withToggleEditState(MyComponent);

但这不起作用,我在编译时收到此错误:

(32,43): Argument of type 'StatelessComponent<IProps>' is not assignable to parameter of type 'ComponentType<IProps & IToggleEditingState & IToggleEditingStateUpdaters>'.
  Type 'StatelessComponent<IProps>' is not assignable to type 'StatelessComponent<IProps & IToggleEditingState & IToggleEditingStateUpdaters>'.
    Type 'IProps' is not assignable to type 'IProps & IToggleEditingState & IToggleEditingStateUpdaters'.
      Type 'IProps' is not assignable to type 'IToggleEditingStateUpdaters'.
        Types of property 'toggleEditing' are incompatible.
          Type '() => void' is not assignable to type 'StateHandler<IToggleEditingState>'.
            Type 'void' is not assignable to type 'Partial<IToggleEditingState> | undefined'.

这是由于在 MyComponent 的 propstoggleEditing中定义的。() => void我解决了这个问题,并且还收到有关缺少索引器的错误。

为了让编译器满意,我需要将MyComponent的 IProps 更改为:

interface IProps {
    className?: string;
    isEditing: boolean;
    toggleEditing: (...payload: any[]) => any;
    [key: string]: any;
}

我必须更改toggleEditing以匹配StateHandler<T>@types/recompose 中定义的 a 类型。我还需要添加索引器。这看起来是因为在 @types/recompose 中,withStateHandlers返回一个InferableComponentEnhancerWithProps<TOutter & TState &TUpdates, TOutter>,最终在您遍历所有类型之后,仍然期望组件上有一个索引器。

我在测试中注意到,他们正在定义 SFC,然后将其全部包装在一个地方。因此,证监会实际上有奇怪的道具要求这一事实并不明显。我想自己定义我的 SFC,所以我可以在其他情况下重用它。我只是超出了预期的用例吗?难道我做错了什么?

4

0 回答 0