如何在 Chakra UI 中进行条件渲染?

How to conditional render in Chakra UI?

我正在渲染两个基于变量加载的 Chakra UI 组件:

{loading ? (<Spinner>) : (<Text color={useColorModeValue('gray.800', 'gray.400')>Hi</Text) }

但是 IDE 警告我: ESLint: React Hook "useColorModeValue" is called conditionally. React Hooks must be called in the exact same order in every component render.

我应该如何渲染这些组件? useColorModeValue 是一个钩子

useColorModeValue 是一个 React hook,所以它不能被条件调用,它打破了 Rules of Hooks。使用三元是一种有条件地调用它的方法。必须在每个渲染周期调用该挂钩。

Only Call Hooks at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

useColorModeValue 拉出到函数组件的主体中,并保存返回的颜色值,以便稍后传递给 Text 组件。

const color = useColorModeValue('gray.800', 'gray.400');

...

{loading ? <Spinner> : <Text color={color}>Hi</Text>}