反应钩子无效的调用钩子

react hooks invalid call hooks

您好,我正在尝试将样式加载到我的 ui 内容中,但我在这方面遇到了麻烦

const useStyles = makeStyles(loginPage)
const classes = useStyles();
const renderTextField = ({
  label,
  input,
  meta: { touched, invalid, error },
  ...custom
}) => (

  <TextField
    label={label}
    placeholder={label}
    variant="outlined"
    InputLabelProps={{
      classes: {
        root: classes.label,
        focused: classes.focusedLabel,
        error: classes.erroredLabel
      }
    }}
    InputProps={{
      classes: {
        root: classes.cssOutlinedInput,
        focused: classes.cssFocused,
        notchedOutline: classes.notchedOutline,
      },
      startAdornment: (
        <InputAdornment position="start">
          <PersonSharpIcon style={{ fontSize: 25  , color: 'rgba(20, 176, 12,0.9)' }} />
        </InputAdornment>
      )
    }}
    error={touched && invalid}
    helperText={touched && error}
    {...input}
    {...custom}
  />
)

错误:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

谁能帮我解决这个问题?

正如错误信息所说。您需要将钩子移到函数组件的主体内。

React 将每个以 'use' 开头的函数视为一个钩子。所以在你的情况下是 useStyles()。 React 还期望这样的函数只能从函数组件的主体内部调用,并且只能从它的根部调用(因此将它嵌套在循环或条件语句中是一个很大的禁忌 - 你可以阅读它 here)。您的函数组件是 renderTextField,因此您可以看到您在 renderTextField 的主体之外调用 useStyles()

像这样构建它应该会有所帮助:

const useStyles = makeStyles(loginPage);
const RenderTextField = ({
    label,
    input,
    meta: { touched, invalid, error },
    ...custom
}) => {
    const classes = useStyles(); // <-- Move it here
    return (
        <TextField
            label={label}
            ...
        >
            ...
        </TextField>
    );
}