2016-05-04 55 views
0
A 
|-B 
| |-C 
| |-D 
| 
|-E 
    |-input 

我有一個組分d這是對組件樹作爲組分E的一個單獨的,較深的,分支當某個動作在d發生(或任何地方在堆棧中),我想集中一個輸入到E.我是否需要使用ref以某種方式存儲對輸入的全局引用,還是有一些更好的方法來使用sagas控制跨越遠處元素的文檔焦點?處理在同級輸入焦點,或遠親,反應的組分

回答

0

這似乎有點特設不知道確切的細節,但在這裏我將如何實現它 -

1)「A」店「isEInputFocused」作爲國家

2)「A」有功能來切換上述狀態值(開/關)並將此功能作爲通道向下傳遞給任何其他想要觸發「E」上的焦點/模糊的組件。例如。

state = { 
    isEFocused: false, 
}; 

toggleEFocus() { 
    this.setState({ isEFocused: !this.state.isEFocused }); 
} 

render() { 
    <div> 
     <D toggleEFocused={ ::this.toggleEFocus } /> 
     <E isEFocused={ this.state.isEFocused } /> 
    </div> 
} 

(雙冒號是綁定功能以便它可以訪問「A」的狀態正確地)

3)「E」,則接收此爲道具從「A」。同樣在「E」componentWillReceiveProps,基於上述prop觸發輸入焦點。

componentWillReceiveProps(nextProps) { 
    if (nextProps.isEFocused) this._inputRef.focus(); 
    else this._inputRef.blur(); 
    // this._inputRef is the ref to the input in E 
} 

4)現在,在 「d」 中,當某些動作情況,只需觸發toggleEFocus()是從 「A」

向下傳遞