In React.js applications that leverage React Router, you may encounter scenarios where you need to pass props to specific handler components. Consider the following application structure:
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var Index = React.createClass({
render: function () {
return (
Some header
);
}
});
var routes = (
);
ReactRouter.run(routes, function (Handler) {
React.render( , document.body);
});
To pass props to the Comments component, you typically use syntax like
One solution is to create a wrapper component that encapsulates both the handler component and the passed-in props:
// CommentWrapper
var CommentWrapper = React.createClass({
render: function () {
return ;
}
});
var routes = (
);
Alternatively, you can leverage class components and the this.props.route object to access props passed to the parent route:
class Index extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
Index - {this.props.route.foo}
);
}
}
var routes = (
);
By setting the foo prop on the / route, you can access the prop later within the Index component using this.props.route.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3