I am trying to create an HOC example in React+Typescript, but my code doesn't work.
This is the HOC component:
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;
And component 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);
I don't get any error, but method itemClicked in Hello.jsx is not triggered when I click div element in ChildHello.tsx.