如何在 Chakra UI 中进行条件渲染?
我正在基于变量加载渲染两个 Chakra UI 组件:
{loading ? (<Spinner>) : (<Text color={useColorModeValue('gray.800', 'gray.400')>Hi</Text) }
但 IDE 警告我这一点: ESLint:React Hook“useColorModeValue”被有条件地调用。在每个组件渲染中必须以完全相同的顺序调用 React Hooks。
我应该如何渲染这些组件? useColorModeValue 是一个钩子
I'm rendering two Chakra UI components based in a variable loading:
{loading ? (<Spinner>) : (<Text color={useColorModeValue('gray.800', 'gray.400')>Hi</Text) }
But the IDE is warning me about this:ESLint: React Hook "useColorModeValue" is called conditionally. React Hooks must be called in the exact same order in every component render.
How should I render those components? useColorModeValue is a hook
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
useColorModeValue
是一个 React hook,因此不能有条件地调用它,它破坏了 Hook 规则。使用三元是一种有条件地调用它的方法。每个渲染周期都必须调用该钩子。将
useColorModeValue
拉出到函数组件的主体中,并保存返回的颜色值,以便稍后传递给Text
组件。useColorModeValue
is a React hook, so it can't be conditionally called, it is breaking the Rules of Hooks. Using a ternary is a way to conditionally call it. The hook must be called each and every render cycle.Pull the
useColorModeValue
out into the body of the function component and save the returned color value to be passed later to theText
component.您可以通过创建一个常量来有条件地渲染 Chakra UI 组件中的属性,该常量接受一个值并根据定义的条件返回所需的属性字符串。这个例子是使用 React 制作的。
我在尝试解决这个问题时准确地用谷歌搜索了标题,但没有找到任何资源。所以我希望这个回答可以帮助遇到同样问题的人。干杯!
You can conditionally render a property within a Chakra UI component by creating a constant that takes a value and returns the desired property string based on defined conditions. This example was made using React.
I googled the title exactly when trying to solve this issue, and found no resources. So I'm hoping this response can help someone who's ran into this same issue. Cheers!