怎样实现像react-router-dom
那样,使用withRouter()
后不用传参的高阶组件?
import React from "react";
import {RouteComponentProps, withRouter} from "react-router-dom";
type Props = {
data: number
}
//高阶组件
const HOC = <P extends Omit<Props, "data">>(WrappedComponent: React.ComponentType<P>) => {
const dataFromContext = 123;//假设这是从context中获取的数据
return (props: P) => {
return (
<div>
<WrappedComponent data={dataFromContext} {...props}/>
</div>
)
}
};
//-----------------
//使用高阶组件
const ComponentA = (props: Props) => {
return (
<div>Context Data: {props.data}</div>
)
};
const A = HOC(ComponentA);
//-----------------
//使用react-router-dom的高阶组件
const ComponentB = (props: RouteComponentProps) => {
return (
<div>{props.location.pathname}</div>
)
};
const B = withRouter(ComponentB);
//-----------------
export const TestPage = () => (
<div>
不需要传参的组件
<A/>{/*报错,提示需要传参数 data */}
<B/>{/*正常*/}
</div>
);
试试这个