【发布时间】:2022-01-23 07:57:52
【问题描述】:
我昨天开始学习 React,遇到了高阶组件的概念。我正在尝试创建一个函数,该函数将现有的Button(来自 MUI 组件库)作为参数,并使用我提供的基本样式返回该按钮的风格化版本。
HOC 的代码:
import React from "react";
import { Button } from "@mui/material";
import { Colors } from "@/constants";
const withBaseStyles = <T extends typeof Button>(
WrappedButton: React.ComponentType<T>
) => {
// At this point, the props being passed in are the original props the component expects.
const StyledButton = (props: T) => (
<WrappedButton
variant="outlined"
size="large"
style={{
backgroundColor: Colors.orangeCompliment,
color: Colors.primary,
borderColor: Colors.primary,
}}
{...props}
/>
);
return StyledButton;
};
export { withBaseStyles };
我尝试使用 HOC 的代码:
import React from "react";
import { Box, Grid, Typography, Button } from "@mui/material";
import { withBaseStyles } from "../OnboardingBaseButton/OnboardingBaseButton";
const OriginalButton = () => <Button>Hello</Button>;
const StyledButton = withBaseStyles(OriginalButton);
const Welcome = () => {
return (
<Grid
container
direction="column"
justifyContent="center"
alignItems="center"
sx={{ height: "100%" }}
>
<div>
<Typography variant="h6" align="center" sx={{ mb: 3 }}>
Welcome PERSON
</Typography>
<Typography variant="subtitle1" align="center" sx={{ p: 2 }}>
We’re thrilled to have you part of our team as we work together to
change the way small businesses communicate with their customers
</Typography>
<Box sx={{ mt: 8, display: "flex", justifyContent: "center" }}>
{/* <OnboardingMainButton variant="onboarding" /> */}
<StyledButton />
</Box>
</div>
</Grid>
);
};
export default Welcome;
这是我得到的错误:
ERROR in src/views/Onboarding/OnboardingSteps/Welcome.tsx:28:12
TS2322: Type '{}' is not assignable to type '(props: { href: string; } & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; color?: "inherit" | "primary" | "secondary" | "success" | "error" | "info" | "warning" | undefined; ... 9 more ...; variant?: "text" | ... 2 more ... | undefined; } & Omit<...> & CommonProps & Omit<...>) => Element'.
Type '{}' provides no match for the signature '(props: { href: string; } & { children?: ReactNode; classes?: Partial<ButtonClasses> | undefined; color?: "inherit" | "primary" | "secondary" | "success" | "error" | "info" | "warning" | undefined; ... 9 more ...; variant?: "text" | ... 2 more ... | undefined; } & Omit<...> & CommonProps & Omit<...>): Element'.
26 | <Box sx={{ mt: 8, display: "flex", justifyContent: "center" }}>
27 | {/* <OnboardingMainButton variant="onboarding" /> */}
> 28 | <StyledButton />
| ^^^^^^^^^^^^
29 | </Box>
30 | </div>
31 | </Grid>
我可能使用了错误的概念来解决我的问题。非常感谢任何帮助!
【问题讨论】:
标签: reactjs typescript material-ui