小编Oka*_*dag的帖子

在 Reactjs 中,如何从父组件操作子组件的子组件?

我想制作一个具有独特模式的高度可重用的反应组件。假设这个联系人列表是由另一个团队制作的;我们无法更改组件,它遵循如下所示的结构。

<Component>
    <Child1 key="child1" />
    <Child2 key="child2" />
    <Child3 key="child3" />
</Component>
Run Code Online (Sandbox Code Playgroud)

示例联系人列表组件:

<ContactList key="contact-list">
    <ContactList.Header key="contactlist-header" />
    <ContactList.Body key="contactlist-body" />
    <ContactList.Footer key="contactlist-footer" />
</ContactList>
Run Code Online (Sandbox Code Playgroud)

我想提供自定义联系人列表组件的选项,例如

  • 在联系人列表中的任意位置添加任何组件
  • 根据“key”值删除组件
  • 更换整个组件

我想公开一些与此类似的 API。

UI.ContactList.remove("contactlist-footer") // 从 ContactList 中删除并存储在变量中以供以后使用

UI.ContactList.add(<CustomContactListFooter/>)// 将 Component 添加到 ContactList 并存储在变量中以供以后使用

其中 UI 是某个命名空间/类

所以我需要一个包装组件,它允许我根据上面的 api 操作 ContactList 的子组件,假设UI.ContactList.remove("contactlist-footer")删除 API 将数据存储在这个变量中_removeRequest = ['contactlist-footer']

在渲染组件时,我不想显示此组件 <ContactList.Footer key="contactlist-footer">,我可以通过像这样的操作在 ContactList 组件中进行操作

高层次的想法:

function ContactList({children}){
    const removeKey =  UI.ContactList._removeRequest[0]
    const newChildren = React.Children.toArray(children).filter(child => child.key !== …
Run Code Online (Sandbox Code Playgroud)

javascript typescript reactjs react-children

5
推荐指数
1
解决办法
1454
查看次数

标签 统计

javascript ×1

react-children ×1

reactjs ×1

typescript ×1