reactjs - React with TypeScript:如何在新组件中访问 HOC 方法
问题描述
嗨,我有一个道具和状态的接口:
interface IOffersProps
{
nextStep: () => void;
step: number
}
export default IOffersProps
interface IOffersState
{}
export default IOffersState;
我创建了一个 HOC,它具有例如 myhocMethod 方法,如下所示:
const addOffersLogic = <TProp extends IOffersProps, TState extends IOffersState>(Component: React.ComponentType<TProp> | React.StatelessComponent<TProp>) =>
class OffersBase extends React.Component<TProp & IOffersProps, TState & IOffersState>
{
constructor(props: TProp & IOffersProps)
{
super(props);
this.myhocMethod= this.myhocMethod.bind(this);
}
myhocMethod= (e: React.MouseEvent<HTMLInputElement, MouseEvent>) : void =>
{
//do something
};
render()
{
return(
<Component {...this.props} />
);
}
}
export default addOffersLogic;
现在在我的新组件中,我无法访问myhocMethod方法。我正在尝试像这样访问它。
class OffersWithoutLogicDesktop extends React.Component<IOffersProps & WithStyles<typeof styles>, IOffersState>
{
constructor(props: IOffersProps & WithStyles<typeof styles>)
{
super(props);
}
render()
{
const css = this.props.classes;
const Body = () =>
<StackPanel>
<HorizontalLinearStepper step={this.props.step} />
Offers
<Button
color="primary"
className={css.button}
onClick={this.myhocMethod}>
Continue
</Button>
<Footer />
</StackPanel>
return Body();
}
}
const OffersDesktop = addOffersLogic(OffersWithoutLogicDesktop);
我的目标是将相同的逻辑放在一个文件中。谢谢
解决方案
为了访问 HOC 中定义的方法,您需要将其作为道具传递给使用 HOC 包装的组件
const addOffersLogic = <TProp extends IOffersProps, TState extends IOffersState>(Component: React.ComponentType<TProp> | React.StatelessComponent<TProp>) =>
class OffersBase extends React.Component<TProp & IOffersProps, TState & IOffersState>
{
constructor(props: TProp & IOffersProps)
{
super(props);
this.myhocMethod= this.myhocMethod.bind(this);
}
myhocMethod= (e: React.MouseEvent<HTMLInputElement, MouseEvent>) : void =>
{
//do something
};
render()
{
return(
<Component {...this.props} myhocMethod={this.myhocMethod}/>
);
}
}
export default addOffersLogic;
class OffersWithoutLogicDesktop extends React.Component<IOffersProps & WithStyles<typeof styles>, IOffersState>
{
constructor(props: IOffersProps & WithStyles<typeof styles>)
{
super(props);
}
render()
{
const css = this.props.classes;
const Body = () =>
<StackPanel>
<HorizontalLinearStepper step={this.props.step} />
Offers
<Button
color="primary"
className={css.button}
onClick={this.props.myhocMethod}>
Continue
</Button>
<Footer />
</StackPanel>
return Body();
}
}
const OffersDesktop = addOffersLogic(OffersWithoutLogicDesktop);
推荐阅读
- javascript - Django-bootstrap-datepicker-plus 未正确呈现日期选择器
- r - 迭代计算 ./ dplyr 函数中大型数据集均值的变异
- python - 在 Python 中使用进程时的空列表
- javascript - Nuxt 定制路由器
- swift - 如何将单元格中的文本字段作为出口快速连接到表格视图单元格类
- python - 使用 Pytorch Mask RCNN 时的零除错误
- python - 来自线性同余随机数的数字 PDF
- r - 如何使用线性假设方程“BI+BI:factor(Year==2018)TRUE=0”进行测试而不会出错?
- c# - .NET Entity Framework Core 中的树实现导致参考问题
- python - Nearest neighbor algorithm