将 props 传递给组件包装器
我有一个在两个子组件之间切换的高阶组件(呈现数据和加载组件的组件): ,问题是如何将数据组件中发生的加载状态传递给临时组件,以便进行条件渲染
Wrapper:
function withLoading<Props>(DataComponent: React.FC<Props>, LoadingComponent: React.FC<Partial<Props>>) {
const newComponent: React.FC<Props & { isLoading: boolean }> = (props) => {
const {
isLoading,
} = props;
if (isLoading) {
return (
<LoadingComponent
{...props}
/>
);
}
return (
<DataComponent
{...props}
/>
);
};
return newComponent;
}
数据和加载组件:
const DataComponent: React.FC<Props> = (props: Props) => {
const fetchData = async (): Promise<void> => {
//Loading Logic happens in this mobx store
await getDataFromBackend();
};
useEffect(() => {
getBranchName();
}, []);
return (
//UI
)
const LoadingComponent = () => {
const {
selectStyle,
} = useStyles(styles);
return (
<SkeletonPlaceholderWrapper>
<View style={styles.loader} />
</SkeletonPlaceholderWrapper>
);
};
export default observer(
withLoading(observer(DataComponent), LoadingComponent) //here the hoc wrapping the two children
),
I have a higher order component that switches between two children (component that renders data and loading component):
,the issue is how to pass the loading state that happens in the data component to the hoc in order to do the conditional rendering
Wrapper:
function withLoading<Props>(DataComponent: React.FC<Props>, LoadingComponent: React.FC<Partial<Props>>) {
const newComponent: React.FC<Props & { isLoading: boolean }> = (props) => {
const {
isLoading,
} = props;
if (isLoading) {
return (
<LoadingComponent
{...props}
/>
);
}
return (
<DataComponent
{...props}
/>
);
};
return newComponent;
}
Data and loading components:
const DataComponent: React.FC<Props> = (props: Props) => {
const fetchData = async (): Promise<void> => {
//Loading Logic happens in this mobx store
await getDataFromBackend();
};
useEffect(() => {
getBranchName();
}, []);
return (
//UI
)
const LoadingComponent = () => {
const {
selectStyle,
} = useStyles(styles);
return (
<SkeletonPlaceholderWrapper>
<View style={styles.loader} />
</SkeletonPlaceholderWrapper>
);
};
export default observer(
withLoading(observer(DataComponent), LoadingComponent) //here the hoc wrapping the two children
),
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在包装器中更改以下内容:
将
if(isLoading)
更改为if(loading)
将函数 setLoading 作为 props 传递给 DataComponent
在 DataComponent 中,更新您的
fetchData< /代码> 方法:
In the wrapper change this :
Change the
if(isLoading)
toif(loading)
Pass the function setLoading as props to DataComponent
In the DataComponent, update your
fetchData
method :