如何在反应 JSS 中将道具传递给 createUseStyles

时间:2021-07-19 16:05:34

标签: reactjs typescript jss

我正在为故事书构建工具提示。我对 JSS 相当陌生。我想通过 props 设置颜色和背景颜色,我命名 textColor 来改变文本的颜色和颜色来改变背景:

interface ITooltipProps {
direction: string;
color: string;
textColor: string;
delay?: number;
children: ReactElement;
content: ReactNode
}



const Tooltip = (props: ITooltipProps): ReactElement | null => {
const {direction, color, textColor} = props;

let timeout: NodeJS.Timeout;
const theme = useTheme();
const classes = useStyles(props);
... 

然而,它似乎一次只对 props 中的一个属性起作用,一旦我尝试引入第二个属性,typescript 就大喊 textColor 不存在:

const useStyles = createUseStyles(() => ({
 tooltipWrapper: {
 display: 'inline-block',
 position: 'relative'
 },
 tooltipTip: {
  position: 'absolute',
  borderRadius: '4px',
  left: '50%',
  transform: 'translateX(-50%)',
  padding: '6px',
  color: (props) => props.textColor || '',  <-- Property 'textColor' does not exist on type '{ 
  color: string; }'

  background: (props) => props.color || '',   <-- works fine

我可以让它工作的唯一方法是在匿名函数之一中显式设置类型以具有这两个属性:

color: (props) => props.textColor || '',  <--- works fine
background: (props: {color: string, textColor: string}) => props.color || '', <--- works fine

知道发生了什么,如果我一次只能获取一个属性,就像在不起作用的例子中一样,我将不胜感激。谢谢

github 存储库链接:https://github.com/luki2000/tooltip

不确定它是否是最干净的解决方案,但通过显式传递它工作的接口:

答案:

color: (props: ITooltipProps) => props.textColor || '',
background: (props: ITooltipProps) => props.color || '',

我可能是错的,但这是我认为以前发生的事情。当我们在 createUseStyles 中设置第一个没有参数类型的匿名函数时,类型是从我们尝试返回的内容中推断出来的,它只包含一个属性“颜色”。这也意味着任何其他匿名函数都必须遵循推断的内容,所以当我尝试执行 props.textColor 时,它说“等等,你在做什么,只有属性颜色!”。

0 个答案:

没有答案
相关问题