React + Typescript中的HOC示例不起作用

时间:2018-12-04 14:23:28

标签: reactjs typescript

我试图在React + Typescript中创建一个HOC示例,但是我的代码不起作用。

codesandbox

这是HOC组件:

Hello.jsx

import * as React from "react";

export interface Props {
  name: string;
  itemClicked: () => void;
}

interface State {
  inc: number;
}

export const makeHello = <P extends Props>(Component: React.ComponentType<P>) =>
  class Hello extends React.Component<Props, State> {
    constructor(props: Props) {
      super(props);

      this.state = {
        inc: 0
      };
    }

    itemClicked = () => {
      this.setState({ inc: inc + 1 }, () => {
        console.log("itemClicked");
      });
    };

    render() {
      return (
        <Component itemClicked={this.itemClicked} {...this.props}>
          Inc state is: {this.state.inc}!
        </Component>
      );
    }
  };

export default makeHello;

和组件ChildHello

import * as React from "react";
import { Props } from "./Hello";
import { makeHello } from "./Hello";

export class ChildHello extends React.Component<Props, {}> {
  static defaultProps = {
    className: ""
  };

  constructor(props: Props) {
    super(props);
  }

  render() {
    return <div onClick={this.props.itemClicked}>Child component</div>;
  }
}

export default makeHello(ChildHello);

我没有收到任何错误,但是当我单击itemClicked中的Hello.jsx元素时,div中的方法ChildHello.tsx没有触发。

1 个答案:

答案 0 :(得分:3)

好像您犯了导入/导出错误。

您是从ChildHello导入命名的类,而不是HOC包装的默认导出。

import * as React from "react";
import { Props } from "./Hello";
import makeHello from "./Hello";

// In index.tsx import { ChildHello } refers to this, not the default export below
export class ChildHello extends React.Component<Props, {}> {
  static defaultProps = {
    className: ""
  };

  constructor(props) {
    super(props);
  }

  render() {
    console.log(this);
    return <div onClick={this.props.itemClicked}>Child component</div>;
  }
}

export default makeHello(ChildHello);

在index.tsx中,确保删除命名的导入

import ChildHello from "./ChildHello";

然后在Hello.tsx中更新itemClicked方法,因为它出错了

// UPDATED added "this.state" to inc
this.setState({ inc: this.state.inc + 1 }, () => {