如何避免在App.js中为我的所有路由使用包装? (使用react-route v4)
App.js
import { Route } from 'react-router-dom'
class App extends Component {
render() {
return (
<div> // <-- I want to avoid this div to have cleaner css
<Route path="/" component={Analytics} />
<Route exact path="/" component={Page_1} />
<Route exact path="/page-2" component={Page_2} />
<Route exact path="/page-3" component={Page_3} />
</div>
)
}
}
Index.js
import { BrowserRouter } from 'react-router-dom'
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
)
答案 0 :(得分:4)
在做出反应之前16你必须这样做,从反应16.2开始,你可以使用Fragments
:见https://reactjs.org/docs/fragments.html
e.g。
render() {
return (
<React.Fragment> //could also be just <>
<Route path="/" component={Analytics} />
<Route exact path="/" component={Page_1} />
<Route exact path="/page-2" component={Page_2} />
<Route exact path="/page-3" component={Page_3} />
<React.Fragment>
)
}
或者如果您愿意,可以返回一系列元素:
render() {
return [
<Route key="1" path="/" component={Analytics} />,
<Route key="2" exact path="/" component={Page_1} />,
<Route key="3" exact path="/page-2" component={Page_2} />,
<Route key="4" exact path="/page-3" component={Page_3} />
]
}
(记得把钥匙放进去)