2017-09-08 50 views
1

我有一個簡單的組件公開了一個名爲doIt的方法,但是這個組件被封裝在一個redux connect中,所以我無法訪問它。這是我簡單的組件:通過引用訪問公開方法

class LoginSwitchDumb extends Component { 
    render() { ... } 
    doIt = (value: boolean) => alert('hi') 
} 

const LoginSwitch = connect(...)(LoginSwitchDumb) 

export LoginSwitch 

我渲染我父母這個元素是這樣的:

render() { 
    return (
     <View> 
      <LoginSwitch id={id} kind={kind} ref={this.refSwitch} /> 
     </View> 
    ) 
} 

refSwitch = el => { 
    console.log('reffing switch:', Object.keys(el)); 
} 

但是我們refSwitch在控制檯日誌中看到,它不給我訪問doIt。如果我不connect我可以訪問它包起來,這是當不connect包裹哪些將記錄:

數組[「道具」,「背景」,「裁判」,「更新」,「 doIt方法 「 」_reactInternalInstance「, 」狀態「]

我們在這裏看到doIt,但是當我connect包裹它,它不存在,我們看到這個:

數組[」道具「,」上下文「,」參考「,」更新「,」版本「,」狀態「,」renderCount「,」商店「,」道具SMODE」, 「setWrappedInstance」, 「選擇」, 「訂閱」, 「notifyNestedSubs」, 「_reactInternalInstance」]

反正是有挖掘這個去doIt

+0

的可能的複製[陣營裁判返回一個「連接」對象,而不是DOM](https://stackoverflow.com/questions/41554365/react-ref-returns-a-connect-object-instead-of-dom) –

回答

1

您可以在包裝組件上調用getWrappedInstance以獲取底層組件實例。爲了做到這一點,還需要在選項傳遞{ withRef: true }connect

const LoginSwitch = connect(..., ..., ..., { withRef: true })(LoginSwitchDumb) 

,並在父:

refSwitch = el => { 
    console.log('reffing switch:', Object.keys(el.getWrappedInstance())); 
} 
+1

Oooo!非常感謝羅斯! – Noitidart

+0

您好,先生,請快速跟隨這個問題。是否更好的做法是像這樣'refSwitch = el => this.switch = el'存儲ref,然後當我需要使用它時,我應該執行'this.el.getWrappedInstance()。BLAH'或者我應該保存實例在裁判所以這樣的:'refSwitch = el => this.switch = el.getWrappedInstance()'? – Noitidart

+0

另外我注意到,還有'el.wrappedInstance'。但是這沒有記錄在https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments-1這是因爲它的性能問題或者什麼,所以我們應該更喜歡'getWrappedInstance'? – Noitidart