React
React Routing
Sök…
Exempel Routes.js-fil, följt av användning av Router Link i komponent
Placera en fil som följande i din toppnivåkatalog. Den definierar vilka komponenter som ska visas för vilka vägar
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import New from './containers/new-post'; import Show from './containers/show'; import Index from './containers/home'; import App from './components/app'; export default( <Route path="/" component={App}> <IndexRoute component={Index} /> <Route path="posts/new" component={New} /> <Route path="posts/:id" component={Show} /> </Route> );
I din toppnivå index.js som är din startpunkt till appen, behöver du bara göra denna routerkomponent så:
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; // import the routes component we created in routes.js import routes from './routes'; // entry point ReactDOM.render( <Router history={browserHistory} routes={routes} /> , document.getElementById('main'));
Nu handlar det helt enkelt om att använda Link
istället för <a>
taggar i hela din applikation. Att använda Link kommer att kommunicera med React Router för att ändra React Router-rutten till den angivna länken, vilket i sin tur kommer att göra rätt komponent enligt definitionen i routes.js
import React from 'react'; import { Link } from 'react-router'; export default function PostButton(props) { return ( <Link to={`posts/${props.postId}`}> <div className="post-button" > {props.title} <span>{props.tags}</span> </div> </Link> ); }
React Routing Async
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Index from './containers/home';
import App from './components/app';
//for single Component lazy load use this
const ContactComponent = () => {
return {
getComponent: (location, callback)=> {
require.ensure([], require => {
callback(null, require('./components/Contact')["default"]);
}, 'Contact');
}
}
};
//for multiple componnets
const groupedComponents = (pageName) => {
return {
getComponent: (location, callback)=> {
require.ensure([], require => {
switch(pageName){
case 'about' :
callback(null, require( "./components/about" )["default"]);
break ;
case 'tos' :
callback(null, require( "./components/tos" )["default"]);
break ;
}
}, "groupedComponents");
}
}
};
export default(
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="/contact" {...ContactComponent()} />
<Route path="/about" {...groupedComponents('about')} />
<Route path="/tos" {...groupedComponents('tos')} />
</Route>
);
Modified text is an extract of the original Stack Overflow Documentation
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow