gpt4 book ai didi

reactjs - 内存动态样式组件会导致 "Rendered fewer hooks than expected error."

转载 作者:行者123 更新时间:2023-12-05 06:16:09 24 4
gpt4 key购买 nike

我正在使用样式组件。我必须使用它来更改样式,因为我需要更改的内容嵌套在 Kendo React Grid 中,正如他们在文档中概述的那样:https://www.telerik.com/kendo-react-ui/components/styling/styled-components/

我需要根据 Prop 动态设置组件的样式。这产生的问题是,因为每个渲染周期都会创建一个新组件,所以文本输入会在您键入时失去焦点。我试图将组件包装在 useMemo 中来解决这个问题,但它会导致“渲染的钩子(Hook)比预期的少”错误。似乎 useRef 是在 styled() 中从 styled-components 调用的,所以当它随后由于 useMemo 而被跳过时,它会导致钩子(Hook)不匹配。

我在这里创建了一个更简单的示例:https://stackblitz.com/edit/react-mu6rlr-omeo5c?file=app%2Fmain.jsx

function CustomText(props){
const [state, setState] = useState('text')
const {color} = props

const Input = styled('input')`
background-color: ${color}
`

return <Input value={state} onChange={useCallback(event => setState(event.target.value))}/>
}
// loses focus on update


function CustomTextMemo(props){
const [state, setState] = useState('memoized')
const {color} = props

const Input = useMemo(
() => styled('input')`
background-color: ${color}
`,
[color]
)

return <Input value={state} onChange={useCallback(event => setState(event.target.value))}/>
}
// "Rendered fewer hooks than expected. This may be caused by an accidental early return statement."

顶部文本框失去了对更新的关注。下层的 memoized 命中 hook 错误。

解决这个问题的更好模式是什么?

最佳答案

正如 Matt Carlotta 在他的评论中指出的那样,我通过在功能组件中定义样式组件来使用反模式。我认为有必要在 props 范围内定义它,以便将 props 用于样式。我在 styled-components 中错过的是您可以将样式定义为 props 的函数,并且它会按预期运行。我用正确的实现更新了示例。

stackblitz.com/edit/react-mu6rlr-omeo5c?file=app%2Fmain.jsx

关于reactjs - 内存动态样式组件会导致 "Rendered fewer hooks than expected error.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62205603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com