我在设置基本的React应用程序时遇到问题,该应用程序允许React Router在各个组件之间使用。当我在App.js中具有以下代码片段时,一切似乎都可以正常工作,但是,我无法将信息传递给子组件。
我试图像这样将JSX对象传递到组件中:
<Main component={Home} />
但是,当尝试访问Main子组件中的属性时,这似乎不起作用。
import React from 'react';
import './App.css';
import { NavLink, Switch, Route } from 'react-router-dom';
import Navigation from './components/navigation.js';
import Main from './components/main.js';
const App = () => (
<div className='app'>
<h1>Portfolio Website</h1>
<Navigation />
<Main home={Home} about={About} />
</div>
);
const Home = () => (
<div className='home'>
<h1>Welcome to my portfolio website</h1>
<p> Feel free to browse around and learn more about me.</p>
</div>
);
const About = () => (
<div className='about'>
<h1>About Me</h1>
</div>
);
export default App;
import React, { Component } from 'react';
import { NavLink, Switch, Route } from 'react-router-dom';
const Main = () => (
<Switch>
<Route exact path='/' component={this.props.Home}></Route>
<Route exact path='/about' component={this.props.About}></Route>
</Switch>
);
export default Main;
import React from 'react';
import { NavLink } from 'react-router-dom';
const Navigation = () => (
<nav>
<ul>
<li><NavLink exact activeClassName="current" to='/'>Home</NavLink></li>
<li><NavLink exact activeClassName="current" to='/about'>About</NavLink></li>
</ul>
</nav>
);
export default Navigation;
我希望我能够使用创建的导航来加载组件内容,就像不在单独的组件中一样。不确定我哪里出错了?谢谢
答案 0 :(得分:1)
我根本不会做这样的事情。我认为您的主要组件是多余的。
这将使您的每个组件都通过此组件。
路由器本身就是一个组件,所以为什么不像下面这样:
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Navigation from "./yournavigationcomponent"
import Home from "./home"
import About from "./about"
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Navigation />
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/about' component={About}/>
</Switch>
</div>
</BrowserRouter>
)
}
}