首頁  >  文章  >  web前端  >  如何將 Props 傳遞給 React Router 中的處理程序元件?

如何將 Props 傳遞給 React Router 中的處理程序元件?

Patricia Arquette
Patricia Arquette原創
2024-10-23 18:44:31455瀏覽

How Can I Pass Props to Handler Components in React Router?

將props 傳遞給React Router 中的處理程序元件

在React Router 中,將props 傳遞給處理程序元件是一個常見的需求。考慮以下結構:

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 myprop="value" />

透過React Router 傳遞Props

但是,在React Router 中,props 必須透過Route 的元件prop 傳遞。有兩種方法可以做到這一點:

1。使用包裝組件

建立一個包裝處理程序組件的包裝組件:

var RoutedComments = React.createClass({
  render: function () {
    return <Comments {...this.props} myprop="value" />;
  }
});

然後,在路由中使用RoutedComments 組件而不是Comments 組件:

<Route path="comments" handler={RoutedComments}/>

2.使用帶有路由屬性的類別元件

定義一個繼承自React.Component 的類別元件並使用元件屬性:

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

以上是如何將 Props 傳遞給 React Router 中的處理程序元件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn