javascript
I have the following structure for my React.js application using React Router:
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);
});
I want to pass some properties into the Comments
component.
(normally I'd do this like <Comments myprop="value" />
)
What's the easiest and right way to do so with React Router?
UPDATE since new release, it's possible to pass props directly via the Route
component, without using a Wrapper
For example, by using render
prop. Link to react router: https://reacttraining.com/react-router/web/api/Route/render-func
Code example at codesandbox: https://codesandbox.io/s/z3ovqpmp44
Component
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>
);
}
}
And usage
<Route path="/greeting/:name" render={(props) => <Greeting text="Hello, " {...props} />} />
OLD VERSION
My preferred way is wrap the Comments
component and pass the wrapper as a route handler.
This is your example with changes applied:
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);
});
如果你不想写包装,我想你可以这样做:
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}/>
);
Copying from the comments by ciantic in the accepted response:
<Route path="comments" component={() => (<Comments myProp="value" />)}/>
This is the most graceful solution in my opinion. It works. Helped me.
链接地址: http://www.djcxy.com/p/52116.html上一篇: reactRouter.withRouter)在以编程方式导航进行反应时不是函数
下一篇: JavaScript的