简体   繁体   English

如何让组件控制 React Native 中的同级组件?

[英]How can I have a component control a sibling component in React Native?

I'm a little new to React Native and making an app.我对 React Native 和制作应用程序有点陌生。 There are three components I'm currently concerned with:我目前关心的三个组件:

  • AllList.js: A screen comprised of a search bar and a FlatList of RowCard.js instances. AllList.js:由搜索栏和 RowCard.js 实例的 FlatList 组成的屏幕。

  • RowCard.js: a custom TouchableHighlight component that displays an item from an API, and currently returns an alert when tapped. RowCard.js:一个自定义的 TouchableHighlight 组件,它显示来自 API 的项目,当前在点击时返回警报。

  • drinkPopup.js: A custom Modal component that needs to take an ID from AllList but be controlled by tapping a RowCard. drinkPopup.js:一个自定义的 Modal 组件,需要从 AllList 中获取一个 ID,但可以通过点击 RowCard 来控制。

I have the list of RowCard instances working, but I need to find a way to make the modal from drinkPopup appear when RowCard is tapped.我有 RowCard 实例的列表正在工作,但我需要找到一种方法来在轻按 RowCard 时让drinkPopup 中的模态出现。 I'm super confused as to how to approach this, since as far as I know props can only be sent from parent to child.我对如何解决这个问题感到非常困惑,因为据我所知,道具只能从父母发送给孩子。

Any suggestions for how to do this?关于如何做到这一点的任何建议? I've looked around to find answers but the results I've found have just been confusing.我环顾四周寻找答案,但我发现的结果令人困惑。

So you need a state that will be accessible by both the drinkPopup and RowCard .因此,您需要一个 state , drinkPopupRowCard都可以访问它。 The way to go is to keep it in their parent ( AllList ) and pass it accordingly. go 的方法是将其保存在其父级( AllList )中并相应地传递它。

So you Parent should be something like:所以你的父母应该是这样的:

const AllList = () => {
    const [visibleModalId, setVisibleModalId] = useState(null)
    return <>
        <RowCard setVisibleModalId={setVisibleModalId}>
        <drinkPopup visibleModalId={visibleModalId}>
    </>
}

That way you can control the modal from RowCard (by calling setVisibleModalId there) and you also know if the drinkPopup should be visible (because it knows if the visibleModalId is null or not)这样,您可以从RowCard控制模态(通过调用setVisibleModalId在那里)并且您还知道drinkPopup是否应该可见(因为它知道visibleModalId是否为 null)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM