Toggle two components using react hooks

二次信任 提交于 2020-06-01 05:07:47

问题


I have two instances of the same component. The component can be opened or closed.

Component has const [isOpen, setIsOpen] = useState(false)

which is being set using useCallback

const openComponent = useCallback(() => {
    setIsOpen(true)
  }, [])

  const closeComponent = useCallback(() => {
    setIsOpen(false)
  }, [])

Components are within their own context. But I have trouble even coming up with an idea how to handle via parent, when one instance opens, close the other conundrum.

Passing state to parent and closing all of them before opening a new one is not an option.

Any ideas?


回答1:


You should lift the state of these two components (open or false) to parent, so parent can have this logic (only one open at a time).

Parent should pass through props the open state to each children, along with a reference to a changeStateHandler(boolean) which children could call to notify the parent that they have been toggled.

So in parent you would have :

const [firstChildState, setFirstChildState] = useState(false);
const [secondChildState, setSecondChildState] = useState(false);

const handlStateChanged = () => {
  // toggle both states
}

[...]

<Child isOpen={firstChildState} onStateChange={handlStateChanged} />
<Child isOpen={secondChildState} onStateChange={handlStateChanged} />

In children :

// calls props.onStateChange on toggle, use props.isOpen to display proper state


来源:https://stackoverflow.com/questions/62046448/toggle-two-components-using-react-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!