【发布时间】:2021-11-06 13:22:02
【问题描述】:
我正忙着让我的打字正确,所以我很好奇是否有人有一个可行的例子或一些关于我哪里出错的反馈。对于createUseStyles 的这个实例,我需要做两件事,接受主题和道具。
我从文档网站上拿了这个例子,当然它已经抛出了 TypeScript 错误,这是可以理解的:
(粘贴屏幕截图只是为了显示打字稿错误)
截图中的代码块:
import React, { ReactNode, CSSProperties } from "react";
import {
createUseStyles,
useTheme,
ThemeProvider,
DefaultTheme,
Styles
} from "react-jss";
interface Props {
children: ReactNode;
useRed: boolean;
}
interface PUTheme {
colorPrimary: string;
altColor: string;
}
const useStyles = createUseStyles({
button: {
background: ({ theme }) => theme.colorPrimary
},
label: {
fontWeight: "bold"
}
});
const Button2: React.FC<Props> = ({ children, ...props }) => {
const theme = useTheme();
console.log(theme);
const classes = useStyles({ ...props, theme });
return (
<button className={classes.button}>
<span className={classes.label}>{children}</span>
</button>
);
};
const theme = {
colorPrimary: "green",
altColor: "red"
};
const App = () => (
<ThemeProvider theme={theme}>
<Button2 useRed={true}>I am a button 2 with green background</Button2>
</ThemeProvider>
);
export default App;
这里发现的错误(错误1)是:
button: {
background: ({ theme }) => theme.colorPrimary
},
“主题”类型上不存在属性“colorPrimary”.ts(2339)
在一定程度上是有道理的——它不知道我们的主题是什么,所以继续……
theme 在此处(错误 2) 发现的错误是:
const classes = useStyles({ ...props, theme });
“默认主题”类型不可分配给“主题”类型。 类型 'null' 不可分配给类型 'Theme'.ts(2322)
马上.. 我有点困惑。但是让我们输入一些内容,看看结果如何......
为我的主题添加界面似乎并没有改变上述任何错误:
interface PUTheme {
colorPrimary: string;
altColor: string;
}
const theme: PUTheme = {
colorPrimary: "green",
altColor: "red"
};
因此,由于向我的主题对象添加接口似乎并没有太大的作用,因此我能够通过添加类型来满足 错误 1 的错误。虽然这让 TypeScript 平静下来,但感觉,错了?
const useStyles = createUseStyles({
button: {
background: ({ theme }: {theme: PUTheme}) => theme.colorPrimary
},
label: {
fontWeight: "bold"
}
});
但是,这仍然给我留下 错误 2,除了错误发生了轻微变化
类型“DefaultTheme”不可分配给类型“PUTheme”。 类型“null”不可分配给类型“PUTheme”
我已尝试跟踪 react-jss 中的输入,但目前这可能超出了我的想象。
是否有人对我做错了什么或工作示例有任何提示或见解?另外,如果您希望看到它的实际效果,这里是我的code sandbox 的链接。
【问题讨论】:
-
请使用代码块而不是代码图像。
-
我解释了为什么它是问题中的屏幕截图。这是为了显示错误发生在哪里。剩下的问题是代码块——这显然是首选。 @LinuxServer
标签: reactjs typescript jss