React
リアクションルーティング
サーチ…
Routes.jsファイルの例、コンポーネント内でのRouter Linkの使用
最上位ディレクトリに次のようなファイルを置きます。どのコンポーネントをどのパスにレンダリングするかを定義します
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>
);
アプリケーションのエントリーポイントであるトップレベルのindex.jsでは、次のようにこのルータコンポーネントだけをレンダリングする必要があります:
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'));
これで、アプリケーション全体で<a>タグの代わりにLinkを使用するだけです。 Linkを使用するとReact Routerと通信し、React Routerの経路を指定されたリンクに変更します。これにより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>
);
}
リアクションルーティング非同期
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
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow