问题
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