0

我正在尝试编写 ReactXP HOC。

这是代码(为了清楚起见,大大简化了):

interface withAuthState {
         //
        }

interface withAuthProps {
         //
        }

const withAuth = <P extends withAuthProps, S extends withAuthState>(
          WrappedComponent: new () => RX.Component<P, S>
        ) =>
          class WithAuth extends RX.Component<P & withAuthProps, S & withAuthState> {
            constructor(props) {
              super(props);
          }

            render() {

              return (
                  <WrappedComponent
                    {...this.props}
                  />
              );
            }
          }
export default withAuth;

现在消费者:

interface signUpProps {
//
}

interface signUpState {
//
}

class SignUp extends RX.Component<signUpProps, signUpState> {
  constructor(props) {
    super(props);
  }
  render() {
    return (<RX.View ... />);
  }
};

export default WithAuth(SignUp);

最后一条导出指令未通过以下错误消息进行编译:

Argument of type 'typeof SignUp' is not assignable to parameter of type 'new () => Component<withAuthProps, withAuthState>'

有很多可能的解决方案,但似乎没有一个对我有用。

任何帮助表示赞赏。谢谢是提前。

4

1 回答 1

0

您为状态键入注释WrappedComponent,它应该是一个带有 0 个参数的构造函数。我的猜测是你想要一个构造函数,它将道具作为构造函数的参数:

const withAuth = <P extends withAuthProps, S extends withAuthState>(
  WrappedComponent: new (props: P) => RX.Component<P, S>
) =>
class WithAuth extends RX.Component<P & withAuthProps, S & withAuthState> {
  constructor(props: P) {
    super(props);
  }

  render() {

    return (
      <WrappedComponent
        {...this.props}
      />
    );
  }
}

//Usage: 

interface withAuthProps {
  auth: boolean
}

interface signUpProps extends withAuthProps {
  test: string;
}
interface signUpState extends withAuthState{}

class SignUp extends RX.Component<signUpProps, signUpState> {
  constructor(props: signUpProps) {
    super(props);
  }
  render() {
    return <div />;
  }
}

const _SignUp = withAuth(SignUp);
let d = <_SignUp test="" auth={true} /> // Will have props from signUpProps
于 2018-03-05T16:53:37.277 回答