簡體   English   中英

React 組件監聽孫子事件

[英]React component listen to grand-children events

我正在開發一個組件庫,其中包括ButtonBarButton組件。

ButtonBar組件將一些Button作為children元素,然后以漂亮的布局呈現它們。

因此,在最基本的情況下,消費代碼將如下所示:

<ButtonBar>
  <Button>First Button</Button>
  <Button>Second Button</Button>
  <Button>Third Button</Button>
</ButtonBar>

ButtonBar一個功能是跟蹤上次單擊的Button並賦予它特殊的樣式。

為了實現這一點, ButtonBar有這樣的代碼:

updateToggle(child) {
  // update state based on child...
}
componentDidMount() {
  this.children = React.Children.map(this.children, (child) => {
    return React.cloneElement(child, {
      press: () => {
        child.props.press();
        this.updateToggle(child);
      }
    })
  });
}

這段代碼試圖利用Buttonpress事件(當它被點擊時由Button自己調用),然后調用ButtonBarupdateToggle函數。

這有點像“擴展”按鈕的按下功能。

無論如何,當用戶執行以下操作時,這種模式就會崩潰:

<ButtonBar>
  <Link to="/"><Button>First Button</Button></Link>
  <Link to="/foo"><Button>Second Button</Button></Link>
  <Link to="/bar"><Button>Third Button</Button></Link>
</ButtonBar>

現在ButtonBar的直接子代不是 Button 類型,我們沒有簡單的方法來確定自定義事件是否發生在Button

ButtonBar應該與它的children交互的方式有什么不同嗎?

如何將 Link 添加為 Button 的屬性?

<ButtonBar>
  <Button to='/'>First Button</Button>
  <Button to="/foo">Second Button</Button>
  <Button to="/bar>Third Button</Button>
</ButtonBar>

您可以強制僅將 Button 作為 Childen 傳遞給 ButtonBar

{React.Children.map( this.props.children, (child, i) => { 
            if (child.type.name === Button.name)
                    React.cloneElement(child, {
                press: () => {
                  child.props.press();
                  this.updateToggle(child);
                }
              })
        })}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM