Adjacent JSX elements must be wrapped in an enclosing tag

走远了吗. 提交于 2019-12-06 05:09:49

问题


I want to have a navigation bar at the bottom and a toolbar at the top of every page in my React-Native app. However, if I create these two elements in the index.ios.js file, I get the error: "Adjacent JSX elements must be wrapped in an enclosing tag". If I put tags surrounding the Navigator and NavBar I just see a blank screen in my app. What should I do? Here is what my render function looks like in index.ios.js

render() {
    return (
      <Navigator
        initialRoute={{name: 'Login'}}
        renderScene={this.renderScene}
        navigationBar={
          <Navigator.NavigationBar
          style={ styles.nav }
          routeMapper={ NavigationBarRouteMapper } />
        }
        />
        <NavBar />
    );
  }

回答1:


When you wrap it in a view make sure you set the flex to 1. My guess is that the view you are giving it has no size and therefore the child elements are inheriting their size from the parent (which is 0)




回答2:


As per React 16, if you wan't to avoid the <View> wrapping, you can return multiple components from render as an array.

return ([
    <Navigator key="navigator" />,
    <NavBar key="navbar" />
]);

Or in a stateless ES6 component:

import React from 'react';

const Component = () => [
  <Navigator key="navigator" />,
  <NavBar key="navbar" />
];

export default Component;

Don't forget the key property as React needs (as for iteration on Array) to be able to discriminate your components.

Edit (Nov. 2018)

Your can also use React.Fragment shorthand:

render() {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );
}



回答3:


Wrap both inside a View and give that outer View wrapper a style of flex 1. Example:

    <View style={{flex: 1}}>
        <Navigator 
           {. . .} 
        />
        <NavBar />
    </View>


来源:https://stackoverflow.com/questions/43196817/adjacent-jsx-elements-must-be-wrapped-in-an-enclosing-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!