reactjs – React – 表达式必须有一个父元素?

前端之家收集整理的这篇文章主要介绍了reactjs – React – 表达式必须有一个父元素?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对React比较陌生,我想知道这里的标准是什么.

想象一下,我有一个像这样的反应路由器:

  1. <Router history={history}>
  2. <Route path="/" component={App}>
  3. <Route path="home component={Home} />
  4. <Route path="about" component={About} />
  5. <Route path="inBox" component={InBox} />
  6. <Route path="contacts" component={Contacts} />
  7. </Route>
  8. </Router>

现在我想删除两条路线,如果prop.mail设置为false,那么这样做的理智方式如下:

  1. <Router history={history}>
  2. <Route path="/" component={App}>
  3. <Route path="home component={Home} />
  4. <Route path="about" component={About} />
  5.  
  6. { if.this.props.mail ?
  7. <Route path="inBox" component={InBox} />
  8. <Route path="contacts" component={Contacts} />
  9. : null }
  10.  
  11. </Route>
  12. </Router>

但是有2条路线和React返回错误

expressions must have one parent element.

我不想在这里使用多个ifs.什么是首选的React处理方式?

将它们放在一个数组中(也分配键):
  1. { if.this.props.mail ?
  2. [
  3. <Route key={0} path="inBox" component={InBox} />,<Route key={1} path="contacts" component={Contacts} />
  4. ]
  5. : null }

使用最新的React版本,您也可以尝试React.Fragment,如下所示:

  1. { if.this.props.mail ?
  2. <React.Fragment>
  3. <Route path="inBox" component={InBox} />,<Route path="contacts" component={Contacts} />
  4. </React.Fragment>
  5. : null }

猜你在找的React相关文章