簡體   English   中英

將自定義道具傳遞給 react-router v4 中的路由器組件

[英]Passing custom props to router component in react-router v4

我正在使用 React Router 創建一個多頁應用程序。 我的主要組件是<App/> ,它將所有路由呈現給子組件。 我正在嘗試通過路由傳遞 props,根據我所做的一些研究,子組件利用傳遞下來的 props 的最常見方法是通過它們繼承的this.props.route對象。 但是,這個對象對我來說是未定義的。 在子組件中的render()函數中,我使用console.log(this.props)並返回一個如下所示的對象

{match: Object, location: Object, history: Object, staticContext: undefined}

看起來完全不像我期望的道具。 這是我的詳細代碼。

父組件(我試圖在我的所有子組件中將“hi”這個詞作為一個名為“test”的道具傳遞下去):

import { BrowserRouter as Router, HashRouter, Route, Switch } from 'react-router-dom';
import Link from 'react-router';
import React from 'react';

import Home from './Home.jsx';
import Nav from './Nav.jsx';
import Progress from './Progress.jsx';
import Test from './Test.jsx';



export default class App extends React.Component {

  constructor() {
    super();

    this._fetchPuzzle = this._fetchPuzzle.bind(this);
  }

  render() {
    return (
      <Router>
        <div>
          <Nav />
          <Switch>
            <Route path="/" exact test="hi" component={Home} />
            <Route path="/progress" test="hi" component={Progress} />             
            <Route path="/test" test="hi" component={Test} />
            <Route render={() => <p>Page not found!</p>} />
          </Switch>
        </div>
      </Router>
    );
  }
}

孩子:

import React from 'react';
const CodeMirror = require('react-codemirror');
import { Link } from 'react-router-dom';

require('codemirror/mode/javascript/javascript')

require('codemirror/mode/xml/xml');
require('codemirror/mode/markdown/markdown');

export default class Home extends React.Component {

  constructor(props) {
    super(props);

    console.log(props)

  }

  render() {
    const options = {
      lineNumbers: true,  
      theme: 'abcdef'    
      // mode: this.state.mode
    };
    console.log(this.props)

    return (
      <div>
        <h1>First page bro</h1>        
        <CodeMirror value='code lol' onChange={()=>'do something'} options={options} />
      </div>);
  }
}

我對 React 還很陌生,所以如果我遺漏了一些明顯的東西,我深表歉意。 謝謝!

您可以通過將render道具用於Route來將道具傳遞給組件,從而內聯您的組件定義。 根據DOCS:

這允許方便的內聯渲染和包裝,而無需上面解釋的不需要的重新掛載。 您可以傳入一個函數,以便在location匹配時調用,而不是使用component prop 為您創建一個新的 React 元素。 渲染道具接收所有與組件渲染道具相同的路由道具

因此,您可以將道具傳遞給組件,例如

 <Route path="/" exact render={(props) => (<Home test="hi" {...props}/>)} />

然后你可以像這樣訪問它

this.props.test 

在您的Home組件中

PS還要確保您正在傳遞{...props}以便默認路由器道具(如location, history, match etc也被傳遞給Home組件,否則唯一傳遞給它的道具是test

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM