React native 如何调用Navigator已安装的组件的方法?

React native 如何调用Navigator已安装的组件的方法?,react-native,React Native,调用onDidFocus()函数后,我想从导航器实例化的组件(场景)调用一个方法 这是我如何实例化导航器的: <Navigator initialRoute={{ name: 'Login' }} renderScene={ this.renderScene } configureScene={(route, routeStack) => Navigator.SceneConfigs.FloatFromRight} onDidFocus={(route

调用
onDidFocus()
函数后,我想从导航器实例化的组件(场景)调用一个方法

这是我如何实例化导航器的:

<Navigator
    initialRoute={{ name: 'Login' }}
    renderScene={ this.renderScene }
    configureScene={(route, routeStack) => Navigator.SceneConfigs.FloatFromRight}
    onDidFocus={(route) => route.component.onFocus()}
    />
但是
route.component.onFocus()
未定义的
,因为(我假定)
route.component
不是对装载的
Login
实例的引用,而是对类型
Login
的引用

那么,我如何获得对已安装组件实例的引用呢


调用
onDidFocus()
方法时,如何调用已装入的组件的方法?

直接调用组件方法是一种不好的做法。若你们只是想抓住组件激活的时刻,你们可以重写
componentDidMount()
方法

或者在更复杂的情况下,您可以在父组件中调用
setState()
,并将新的道具传递给
Login
。大概是这样的:

Navigator.sceneconfig.FloatFromRight}
onDidFocus={(路由)=>this.setState({currentRoute:route})}/>
renderScene(路线、导航器){
返回
}

然后在
Login
组件中捕获新的道具,覆盖
componentWillReceiveProps()

就像@farwayer建议的那样,从组件调用函数是不好的做法,因为它是耦合的代码

最后,我使用我们自己的事件总线通知任何相关方,过渡已经结束

onDidFocus(){
    EventBus.ref().emit('NAVIGATOR_TRANSITION_END')
}

render() {
    return (
        <Navigator
            ...
            onDidFocus={ this.onDidFocus }
            />
    )
}
onDidFocus(){
EventBus.ref()发出('NAVIGATOR\u TRANSITION\u END')
}
render(){
返回(
)
}

您的代码不起作用,因为
renderScene
onDidFocus
之前被调用,因此
这个.state.currentRoute
未定义的
。它的概念是您可以更改parrent组件的状态,并将任何新的道具传递给子组件,即使您将
route
传递给该组件(或任何其他道具)它不能解决问题。那么问题是什么?为什么需要在
onDidFocus
回调上调用子组件方法?问题在我的问题中描述。
onDidFocus(){
    EventBus.ref().emit('NAVIGATOR_TRANSITION_END')
}

render() {
    return (
        <Navigator
            ...
            onDidFocus={ this.onDidFocus }
            />
    )
}