在 react-router v4 中将自定义道具传递给路由器组件

Passing custom props to router component in react-router v4

我正在使用 React Router 创建一个多页面应用程序。我的主要组件是 <App/>,它将所有路由渲染到 child 组件。我正在尝试通过路由传递道具,并且基于我所做的一些 research,child 组件利用向下传递的道具的最常见方式是通过 this.props.route object 他们继承。但是,这个 object 对我来说是未定义的。在 child 组件中的 render() 函数中,我 console.log(this.props) 是 return 一个看起来像这样的 object

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

看起来完全不像我预期的道具。这是我的详细代码。

Parent 组件(我试图在我的所有 child 组件中将 "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>
    );
  }
}

Child:

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 来将属性传递给组件,从而内联您的组件定义。根据the DOCS:

This allows for convenient inline rendering and wrapping without the undesired remounting explained above.Instead of having a new React element created for you using the component prop, you can pass in a function to be called when the location matches. The render prop receives all the same route props as the component render prop

所以你可以像这样将 prop 传递给组件

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

然后你就可以像

一样访问它了
this.props.test 

在您的 Home 组件中

P.S. Also make sure that you are passing {...props} so that the default router props like location, history, match etc are also getting passed on to the Home component otherwise the only prop that is getting passed down to it is test.