」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何將 Props 傳遞給 React Router 中的處理程序元件?

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

發佈於2024-11-08
瀏覽:363

How to Pass Props to Handler Components in React Router?

使用React Router 將Props 傳遞給處理程序元件

在利用React Router 的React.js 應用程式中,您可能會遇到需要將props 傳遞給特定處理程序組件的場景。考慮以下應用程式結構:

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

要將屬性傳遞給 Comments 元件,通常使用 等語法。然而,這種方法與 React Router 不相容,React Router 期望處理程序元件是純函數或類別元件。

一個解決方案是建立一個包裝器元件,封裝處理程序元件和傳入的 props:

// CommentWrapper
var CommentWrapper = React.createClass({
  render: function () {
    return ;
  }
});

var routes = (
  
    
    
  
);

或者,您可以利用類別元件和 this.props.route 物件來存取傳遞給父路由的 props:

class Index extends React.Component { 

  constructor(props) {
    super(props);
  }
  render() {
    return (
      

Index - {this.props.route.foo}

); } } var routes = ( );

透過在 / 路由上設定 foo 屬性,您可以稍後在 Index 元件中使用 this.props.route.

存取該屬性
版本聲明 本文轉載於:1729674935如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3