在组件上处理NavigatorIOS路由

Bla*_*kus 14 javascript ios react-native

我正在尝试在React Native中构建一个非常简单的Todo应用程序.它由两个视图组成:一个具有任务列表,一个具有输入字段(用于添加新视图).通过NavigatorIOS它上面的按钮确保导航(可以UIBarButtonItem使用UIKit).

在列表视图中,导航器上有一个添加右按钮,在带有文本字段的视图上,左侧有后退按钮,右侧有一个完成后按钮.单击"完成"时,应添加包含文本字段内容的新任务.

问题是,在创建NavigatorIOS组件时定义了按钮及其操作,我找不到将另一个组件中定义的方法作为按钮操作附加的方法.

举个例子,这是我的 NavigatorIOS

class TodoList extends Component {

    render() {
        return (
            <NavigatorIOS
                ref="nav"
                style={styles.navbar}
                initialRoute={{
                    component: ItemList,
                    title: 'Todo list',
                    rightButtonTitle: 'Add',
                    onRightButtonPress: () => {
                        this.refs.nav.push({
                            title: 'Add a new task',
                            component: AddTodo,
                            rightButtonTitle: 'Done',
                            onRightButtonPress: () => {
                                console.log('done !');
                            }
                        });
                    }
                }}
            />
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我没有把我的另外两个组件放在这里ItemList,AddTodo因为它没有任何有趣的东西.

我需要的是一种使组件与导航组件进行通信(如委托模式)的方法.

也许这是不可能的,或者我对React Native使用的范例完全错误,所以如果我的问题不清楚,请随意评论.

编辑05/26

实际上,Facebook团队意识到缺少用NavigatorIOS组件处理该用例的东西.

来自Eric Vicenti(2015年2月3日发布)关于GitHub上的一个问题,它完全涵盖了我的问题.

目前最好的方法是EventEmitter在所有者中创建一个NavigatorIOS,然后你可以将它传递给孩子使用route.passProps.孩子可以混入Subscribable.Mixin,然后进入componentDidMount,你可以

this.addListenerOn(this.props.events, 'myRightBtnEvent', this._handleRightBtnPress);
Run Code Online (Sandbox Code Playgroud)

很明显,这个API需要改进.我们正在积极地在Relay中使用路由API,并希望反应路由器,但我们希望NavigatorIOS可以独立使用.也许我们应该在导航器对象中添加一个事件发射器,因此子组件可以订阅各种导航器活动:

this.addListenerOn(this.props.navigator.events, 'rightButtonPress', this._handleRightBtnPress);
Run Code Online (Sandbox Code Playgroud)

Jic*_* Wu 1

A. 在初始组件中

this.props.navigator.push({
    title: 'title',
    component: MyComponent,
    rightButtonTitle: 'rightButton',
    passProps: {
        ref: (component) => {this.pushedComponent = component},
    },
    onRightButtonPress: () => {
        // call func
        this.pushedComponent && this.pushedComponent.myFunc();
    },
});
Run Code Online (Sandbox Code Playgroud)

B. 在推送组件中
替换推送组件中的 onRightButtonPress 函数。

componentDidMount: function() {
    // get current route
    var route = this.props.navigator.navigationContext.currentRoute;
    // update onRightButtonPress func
    route.onRightButtonPress =  () => {
        // call func in pushed component
        this.myFunc();
    };
    // component will not rerender
    this.props.navigator.replace(route);
},
Run Code Online (Sandbox Code Playgroud)