React - expressions must have one parent element?

后端 未结 7 1403
再見小時候
再見小時候 2020-11-30 02:02

I\'m relatively new to React and I\'m wondering what\'s the standard here.

Imagine I have a react-router like this one:



        
相关标签:
7条回答
  • 2020-11-30 02:45

    Faced the same error in a similar situation (React Native).

    export default class App extends React.Component {
      render() {
        return (
          <StatusBar barStyle="default" />
          <AppContainer />
        );
      }
    }
    

    As indicated in the error prompt the JSX expression requires to have one parent element, hence wrap the elements in the return expression with a parent element. The flex: 1 style was added to allow the <View> element assume the height of the entire screen.

    export default class App extends React.Component {
      render() {
        return (
          <View style={{flex: 1}}>
            <StatusBar barStyle="default" />
            <AppContainer />
          </View>
        );
      }
    }
    
    0 讨论(0)
  • You can leverage short hand fragments to return a list of children along with Logical '&&' Operator for conditional rendering. Nice and clean!

    0 讨论(0)
  • 2020-11-30 02:55

    You must been use a fragment tag e.g(div, <>,...).

    Check this short solution:

    { if.this.props.mail ? 
     <>
       <Route path="inbox" component={Inbox} />
       <Route path="contacts" component={Contacts} />
     </>
     : null }
    
    0 讨论(0)
  • 2020-11-30 03:01

    just try enclosing the code after the return statement in an element like <div>....code </div>,etc.

    eg:-

    const Div =()=>{
               return
                <div>
                  <Button name="Save" ></Button>
                  <Button name="Edit"></Button>
                  <Button name="Cancel"></Button>  
                </div>}
    
    0 讨论(0)
  • 2020-11-30 03:07

    Put them in an array (assign the keys also):

    { if.this.props.mail ? 
        [
            <Route key={0} path="inbox" component={Inbox} />,
            <Route key={1} path="contacts" component={Contacts} />
        ]
    : null }
    

    With latest React version, you can try React.Fragment also, like this:

    { if.this.props.mail ? 
        <React.Fragment>
            <Route path="inbox" component={Inbox} />,
            <Route path="contacts" component={Contacts} />
        </React.Fragment>
    : null }
    
    0 讨论(0)
  • 2020-11-30 03:08

    2020 update

    I have checked out every solution from answers. Here is the breakdown for regular React:

    1. React Fragment

    When i wanted to use it once, without adding additional DOM node - it worked. When i tried to use second React.Fragment got really bad errors. Wasn't able to fix it.

    2. View

    I was unable to import View properly. I don't know if this is only for Reactjs, or Native, but this does not work

    3. Div

    What actually worked was to put HTML into Div

    0 讨论(0)
提交回复
热议问题