属性 x 在类型 '(props?: any) => ClassNameMap<"x">' 上不存在

property x does not exist on type '(props?: any) => ClassNameMap<"x">'

我必须根据参数创建样式,为此我已按以下方式完成。

 const useStyles = (isLayoutReadOnly = false) =>
  makeStyles((theme: Theme) => {
    return {
      x: {
        margin: theme.spacing(0, 0, 1, 0),
          marginLeft: !isLayoutReadOnly ? '-20px' : undefined 
        }
      }
    };
  });

我正在尝试以这种方式使用它,

 const { x } = useStyles(isLayoutReadOnly);

这让我出错

property x does not exist on type '(props?: any) => ClassNameMap<"x">'

我该如何解决这个问题?我试过设置自定义 return 类型和 ReturnType<typeof makeStyles>,但是,它无法检测到。

您正在将 useStyles 设置为 调用 makeStyles:

的函数
const useStyles = (isLayoutReadOnly = false) => makeStyles()...

docs 中的示例显示 useStyles 直接 设置为 makeStyles 而不是函数:

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      backgroundColor: theme.palette.red,
    },
  }),
);

您可以使用 Immediately Invoked Function Expression 用您的代码实现相同的模式。通过 将您的函数包装在 (() => {}) 括号中,然后在末尾添加 () 括号 ,您可以立即调用您的函数以确保 useStyles 获得return 您的 (isLayoutReadOnly) => ... 函数的值。这是它的样子:

  const useStyles = ((isLayoutReadOnly = false) =>
  makeStyles((theme) => {
    return {
      x: {
        margin: theme.spacing(0, 0, 1, 0),
          marginLeft: !isLayoutReadOnly ? '-20px' : undefined 
        }
      }
  }))(isLayoutReadOnly);

另一个选项是调整您的呼叫方式 useStyles。您可以在对 useStyles 的调用中添加一组额外的括号,以 调用 returned 的函数以获得预期的行为:

  const  {x}  = useStyles(isLayoutReadOnly)();