我想知道您如何使用ReactJS设置每个页面的标题。还有更多,我使用react-router-component,并且我想使用相同的技术通过使用React.renderComponentToString为服务器端的每个页面设置标题。
我当前的根组件:
module.exports = App = React.createClass
getInitialState: ->
return title: 'My title'
render: ->
<html lang="fr">
<head>
<link rel="stylesheet" href="/assets/css/main.css" />
<script src="/assets/js/bundle.js"></script>
<title>{@state.title}</title>
</head>
<body>
<div id="body-content">
<div id="main-container">
<Content path={@props.path} />
</div>
</div>
</body>
</html>
和我的内容组件:
Content = React.createClass
render: ->
<Locations id="main" className="App" path={@props.path}>
<Location path="/" handler={MainPage} />
<Location path="/users/:username" handler={UserPage} />
</Locations>
最佳答案
顶级React组件
var React = require('react');
var AppStore = require('../stores/AppStore');
var Application = React.createClass({
propTypes: {
path: React.PropTypes.string.isRequired,
onSetTitle: React.PropTypes.func.isRequired
},
render() {
var page = AppStore.getPage(this.props.path);
this.props.onSetTitle(page.title);
return (
<div className="container">
<h1>{page.title}</h1>
<div return <div dangerouslySetInnerHTML={{__html: page.body}}>;
</div>
);
}
});
module.exports = Application;
客户端启动脚本(入口点)
var React = require('react');
var Dispatcher = require('./core/Dispatcher');
var Application = require('./components/Application');
Dispatcher.register((payload) => {
var action = payload.action;
if (action.actionType === ActionTypes.CHANGE_LOCATION) {
app.setProps({path: action.path});
}
});
var app = React.createElement(Application, {
path: window.location.pathname,
onSetTitle: (title) => document.title = title
}));
app = React.render(app, document.body);
更多信息:https://gist.github.com/koistya/24715d295fbf710d1e24
演示项目:https://github.com/kriasoft/react-starter-kit