对于使用React.js的反应路由器应用程序,我的结构如下
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var Index = React.createClass({
render: function () {
return (
<div>
<header>Some header</header>
<RouteHandler />
</div>
);
}
});
var routes = (
<Route path="/" handler={Index}>
<Route path="comments" handler={Comments}/>
<DefaultRoute handler={Dashboard}/>
</Route>
);
ReactRouter.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});我想将一些属性传递到Comments组件中。
(通常我会像<Comments myprop="value" />一样这样做)
用React路由器做这件事最简单和正确的方法是什么?
发布于 2015-01-09 20:18:54
更新
自从新版本发布以来,可以直接通过Route组件传递道具,而无需使用包装器。例如,由道具。
组件:
class Greeting extends React.Component {
render() {
const {text, match: {params}} = this.props;
const {name} = params;
return (
<React.Fragment>
<h1>Greeting page</h1>
<p>
{text} {name}
</p>
</React.Fragment>
);
}
}使用:
<Route path="/greeting/:name" render={(props) => <Greeting text="Hello, " {...props} />} />旧版本
我喜欢的方法是包装Comments组件并将包装器作为路由处理程序传递。
下面是应用更改的示例:
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var CommentsWrapper = React.createClass({
render: function () {
return (
<Comments myprop="myvalue"/>
);
}
});
var Index = React.createClass({
render: function () {
return (
<div>
<header>Some header</header>
<RouteHandler/>
</div>
);
}
});
var routes = (
<Route path="/" handler={Index}>
<Route path="comments" handler={CommentsWrapper}/>
<DefaultRoute handler={Dashboard}/>
</Route>
);
ReactRouter.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});发布于 2015-09-24 12:56:32
如果您不想编写包装器,我想您可以这样做:
class Index extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>
Index - {this.props.route.foo}
</h1>
);
}
}
var routes = (
<Route path="/" foo="bar" component={Index}/>
);发布于 2016-08-18 20:44:34
从古兰地在已接受的回复中的评论复制:
<Route path="comments" component={() => (<Comments myProp="value" />)}/>在我看来,这是最优雅的解决办法。它起作用了。帮了我。
https://stackoverflow.com/questions/27864720
复制相似问题