[英]How can I pass down variables into child component so that they work with React Router?
I am having issues setting up a basic React application that allows React Router to be used across components. 我在设置基本的React应用程序时遇到问题,该应用程序允许在组件之间使用React Router。 When I have the below code snippets in App.js it all seems to work fine, however, I'm having trouble passing information down to child components. 当我在App.js中具有以下代码片段时,一切似乎都可以正常工作,但是,我无法将信息传递给子组件。
I've tried passing the JSX objects into the component like so: 我试过像这样将JSX对象传递到组件中:
<Main component={Home} />
But this hasn't seemed to work when trying to access the properties within the Main child component. 但这似乎在尝试访问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;
I expected that I would be able to use the navigation created to load the component content in as it does when not in separate components. 我希望我将能够使用创建的导航来加载组件内容,就像不在单独的组件中一样。 Not sure where I've gone wrong? 不确定我哪里出错了? Thanks 谢谢
I would not have done anything like this at all. 我根本不会做这样的事情。 I think that your Main component is redundant. 我认为您的主要组件是多余的。
This will lead to put every single one of your components through this component. 这将导致您的每个组件都通过此组件。
The router is a component in itself, so why not something like the following: 路由器本身就是一个组件,所以为什么不这样呢?
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>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.