我试图在React + Typescript中创建一个HOC示例,但是我的代码不起作用。
这是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
没有触发。
答案 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 }, () => {