react.js - react-routers 如何同时渲染两个位置?
本文介绍了react.js - react-routers 如何同时渲染两个位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
主要是两个问题:
架构是 express+swig_nodejs+react+react-router
请大家看
index.html
,我想同时渲染<title>
和<body>
里的一个位置,如何传递<title>
的值?希望这个值可以由 react.js 动态给出第二个问题是如何选择性的渲染
index.htm
l 和另一个 html 模板,比如我想让访问 /index 时渲染用 App-Index 这个组件渲染index.html
,然后访问 /regist 时用 App-Regist 渲染regist.html
this is the server.js
about router settings:
app.use(function(req, res) {
Router.run(routes, req.path, function(Handler) {
var html = React.renderToString(React.createElement(Handler));
var page = swig.renderFile('views/index.html', { html: html});
res.send(page);
});
});
this is the /app/routes.js
:
import React from 'react';
import {Route} from 'react-router';
import App from './components/App';
import Home from './components/Home';
import Regist from './components/Regist';
export default (
<Route handler={App}>
<Route path='/' handler={Home} />
<Route path='/regist' handler={Regist} />
</Route>
);
this is the /app/main.js
:
import React from 'react';
import Router from 'react-router';
import routes from './routes';
Router.run(routes, Router.HistoryLocation, function(Handler) {
React.render(<Handler />, document.getElementById('app'));
});
this is the /app/App.js
:
import React from 'react';
import {RouteHandler} from 'react-router';
class App extends React.Component {
render() {
return (
<RouteHandler />
);
}
}
export default App;
this is the /view/index.html
, I want to set {{title}}
and {{html|safe}}
at the same time
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>{{title}}</title>
<link rel="stylesheet" href="/css/amazeui.css"/>
</head>
<body>
<div id="app">{{ html|safe }}</div>
<script src="/socket.io/socket.io.js"></script>
<script src="/js/vendor.js"></script>
<script src="/js/vendor.bundle.js"></script>
<script src="/js/bundle.js"></script>
</body>
</html>
解决方案
如果想要修改 title 的话推荐使用 react sideeffects 相关的组件,GitHub 上面都有自己可以搜一下
这篇关于react.js - react-routers 如何同时渲染两个位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文