react-router - 将props传递给处理程序组件

react-router  - 将props传递给处理程序组件

问题描述:

我使用 React Router 为我的React.js应用程序提供了以下结构:

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.

(通常我会这样做< Comments myprop =value/>

React Router最简单,最正确的方法是什么?

What's the easiest and right way to do so with React Router?




UPDATE 自新版本发布以来,可以通过 Route 组件直接传递道具,而无需使用包装器


UPDATE since new release, it's possible to pass props directly via the Route component, without using a Wrapper

例如,使用 render prop。反应路由器的链接: https://reacttraining.com/react-router/ web / api / Route / render-func

For example, by using render prop. Link to react router: https://reacttraining.com/react-router/web/api/Route/render-func

codesandbox的代码示例: https://codesandbox.io/s/z3ovqpmp44

Code example at codesandbox: https://codesandbox.io/s/z3ovqpmp44

组件

    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} />} />






OLD VERSION

我首选的方法是包装 Comments 组件并将包装器作为路由处理程序传递。

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);
});