[英]How to display two react components
This is my first time using React and need some help.这是我第一次使用 React,需要一些帮助。 I have a TextEditor component and a Navbar component in my App.js class.我的 App.js 类中有一个 TextEditor 组件和一个 Navbar 组件。 I am trying to get both to display on my page, but only see the TextEditor component.我试图让两者都显示在我的页面上,但只能看到 TextEditor 组件。 When this component is removed i can then see the Navbar component.删除此组件后,我可以看到 Navbar 组件。 How can i see both components on my page?如何在我的页面上看到这两个组件?
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Switch>
{/* Navbar */}
<Route exact path="/" component={Navbar} />
<Navbar bg="light" expand="sm"/>
{/* Home page */}
<Route path="/" exact>
<Redirect to={`/documents/${uuidV4()}`} />
</Route>
{/* TextEditor */}
<Route path="/documents/:id" component={TextEditor}>
<TextEditor />
</Route>
</Switch>
</div>
</Router>
)
}
}
try this code, this add header on every your page with put component Navbar outside Switch试试这个代码,这会在每个页面上添加标题,并在 Switch 外放置组件 Navbar
class App extends Component {
render() {
return (
<Router>
<div className="App">
{/* Navbar */}
<Navbar bg="light" expand="sm"/>
<Switch>
{/* Home page */}
<Route exact path="/">
<Redirect to={`/documents/${uuidV4()}`} />
</Route>
{/* TextEditor */}
<Route path="/documents/:id" component={TextEditor}>
<TextEditor />
</Route>
</Switch>
</div>
</Router>
)
}
}
or add header just with component TextEditor instead或仅使用组件 TextEditor 添加标题
class App extends Component {
render() {
return (
<Router>
<Switch>
{/* Home page */}
<Route exact path="/">
<Redirect to={`/documents/${uuidV4()}`} />
</Route>
{/* TextEditor */}
<Route path="/documents/:id" component={TextEditor}>
{/* Navbar */}
<Navbar bg="light" expand="sm"/>
<TextEditor />
</Route>
</Switch>
</Router>
)
}
}
You Need to use a fragment to wrap everything in the return statement in. It is basically just an empty html tag as seen below.您需要使用一个片段来包装 return 语句中的所有内容。它基本上只是一个空的 html 标签,如下所示。
https://reactjs.org/docs/fragments.html https://reactjs.org/docs/fragments.html
class App extends Component {
render() {
return (
<>
<Router>
<div className="App">
<Switch>
{/* Navbar */}
<Route exact path="/" component={Navbar} />
<Navbar bg="light" expand="sm"/>
{/* Home page */}
<Route path="/" exact>
<Redirect to={`/documents/${uuidV4()}`} />
</Route>
{/* TextEditor */}
<Route path="/documents/:id" component={TextEditor}>
<TextEditor />
</Route>
</Switch>
</div>
</Router>
</>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.