使用反应钩子切换两个组件 [英] Toggle two components using react hooks

查看:59
本文介绍了使用反应钩子切换两个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相同组件的实例.组件可以打开或关闭.

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

组件有 const [isOpen, setIsOpen] = useState(false)

这是使用 useCallback 设置的

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.

有什么想法吗?

推荐答案

你应该将这两个组件的状态(open 或 false)提升到 parent,这样 parent 就可以有这个逻辑(一次只打开一个).

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 应该通过 props 将 open 状态传递给每个孩子,以及对 changeStateHandler(boolean) 的引用,孩子可以调用它来通知父母他们已经被切换.

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.

所以在父母中你会有:

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} />

在儿童中:

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

这篇关于使用反应钩子切换两个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆