[英]React component listen to grand-children events
我正在開發一個組件庫,其中包括ButtonBar
和Button
組件。
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);
}
})
});
}
這段代碼試圖利用Button
的press
事件(當它被點擊時由Button
自己調用),然后調用ButtonBar
的updateToggle
函數。
這有點像“擴展”按鈕的按下功能。
無論如何,當用戶執行以下操作時,這種模式就會崩潰:
<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.