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

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

{匹配:对象,位置:对象,历史:对象,静态上下文:未定义}

看起来根本不像我预期的道具.这是我的详细代码.

父组件(我试图在我的所有子组件中将hi"这个词作为一个名为test"的道具传递):

import { BrowserRouter as Router, HashRouter, Route, Switch } from 'react-router-dom';从'react-router'导入链接;从反应"导入反应;从'./Home.jsx'导入主页;从'./Nav.jsx'导入导航;从'./Progress.jsx'导入进度;从'./Test.jsx'导入测试;导出默认类 App 扩展 React.Component {构造函数(){极好的();this._fetchPuzzle = this._fetchPuzzle.bind(this);}使成为() {返回 (<路由器>

<导航/><开关><Route path="/" 精确测试="hi" component={Home}/><Route path="/progress" test="hi" component={Progress}/><Route path="/test" test="hi" component={Test}/><路线渲染={() =><p>找不到页面!</p>}/></开关></div></路由器>);}}

孩子:

从'react'导入反应;const CodeMirror = require('react-codemirror');从'react-router-dom'导入{链接};要求('codemirror/mode/javascript/javascript')要求('codemirror/mode/xml/xml');require('codemirror/mode/markdown/markdown');导出默认类 Home 扩展 React.Component {构造函数(道具){超级(道具);控制台日志(道具)}使成为() {常量选项 = {行号:真,主题:'abcdef'//模式:this.state.mode};控制台.log(this.props)返回 (

<h1>首页兄弟</h1><CodeMirror value='code lol' onChange={()=>'做点什么'} options={options}/></div>);}}

我对 React 很陌生,所以如果我遗漏了一些明显的东西,我深表歉意.谢谢!

解决方案

您可以通过使用 render 属性将属性传递给组件到 Route,从而内联您的组件定义.根据文档:

<块引用>

这允许方便的内联渲染和包装,而无需上面解释了不希望的重新安装.而不是拥有一个新的 React使用 component 属性为你创建的元素,你可以传入一个location 匹配时调用的函数.渲染道具接收所有与组件渲染道具相同的路由道具

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

 <Route path="/" 精确渲染={(props) =>(<Home test="hi" {...props}/>)}/>

然后你就可以访问它了

this.props.test

在您的 Home 组件中

<块引用>

P.S. 还要确保您传递 {...props} 以便location、history、match 等默认路由器 props 也被传递给 Home 组件否则,唯一传递给它的道具是 test.

I'm using React Router to create a multi page app. My main component is <App/> and it renders all of the routing to to child components. I'm trying to pass props via the route, and based on some research I did, the most common way for child components to tap into props passed down is via the this.props.route object that they inherit. However, this object is undefined for me. On my render() function in the child component, I console.log(this.props) and am return an object that looks like this

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

Doesn't look like the props I expected at all. Here is my code in detail.

Parent Component (I'm trying to pass the word "hi" down as a prop called "test" in all of my child components):

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

I'm pretty new to React so my apologies if I'm missing something obvious. Thanks!

解决方案

You can pass props to the component by making use of the render prop to the Route and thus inlining your component definition. According to 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

So you can pass the prop to component like

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

and then you can access it like

this.props.test 

in your Home component

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.

相关文章