首页 > 解决方案 > 在导航栏上反应原生渲染视图

问题描述

我有一个带有反应导航的应用程序,我想在导航栏上进行绘制。我的 app.js 看起来像这样:

export default class App extends React.Component {
    render() {
        return (
            <Provider store={store}>
                <StatusBar barStyle='dark-content'></StatusBar>
                <Navigation />
            </Provider>
        )
    }
}

...
const AppNavigator = createStackNavigator({
    Home: HomeView,
    Detail: DetailView
},

let Navigation = createAppContainer(AppNavigator)

在作为根组件的 HomeView 中,我的渲染方法如下所示:

    render() {
        return (
             <View style={{ flex: 1, backgroundColor: colors.backgroundColor }}>

                  {isModalVisible && <View style={styles.overlay}>
                                          ... Modal content
                                     </View>}
                  ... Other views
             </View>
        )
    }

overlay: {
    position: 'absolute',
    zIndex: 1,
    top: 0,
    left: 0,
    width: Dimensions.get('screen').width,
    bottom: 0,
    backgroundColor: '#000000A0',
},

我的问题是,模态视图不会在导航栏上呈现,即栏不在覆盖之下。我不能使用内置模式或 react-native-modal,有什么方法可以使用常规视图在导航栏上呈现?

标签: reactjsreact-nativereact-navigation

解决方案


我最终从与导航项处于同一级别的根容器中显示模态视图。

RootContainer.js:

render() {
    return (
        <View style={{ flex: 1 }}>
            <StatusBar barStyle='dark-content'></StatusBar>
            <Navigation />

            {isModalVisible && <View style={styles.overlay}>
                                      ... Modal content
                               </View> } />}
        </View>
    )
}

...
const AppNavigator = createStackNavigator({
    Home: HomeView,
    Detail: DetailView
},

let Navigation = createAppContainer(AppNavigator)

App 渲染 RootContainer:

export default class App extends React.Component {
    render() {
        return (
            <Provider store={store}>
                <RootContainer />
            </Provider>
        )
    }
}

这不是最佳解决方案,因为您将数据从组件一直传送到根目录。但这是反应导航的已知缺点之一。你可以在这里看到一些想法和讨论https://github.com/react-navigation/react-navigation/issues/363

对于像我这样使用 redux 的人来说:您必须再嵌套一层(不是渲染屏幕或 App 中的 modal,而是 RootContainer),因为 redux 不允许在 App 中创建 store 并同时使用 connect。参考:https ://stackoverflow.com/a/41892948/837244


推荐阅读