将自定义道具传递给 react-router v4 中的路由器组件 [英] Passing custom props to router component in react-router v4

查看:26
本文介绍了将自定义道具传递给 react-router v4 中的路由器组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React Router 创建一个多页面应用程序.我的主要组件是 并将所有路由呈现给子组件.我正在尝试通过路线传递道具,并基于一些研究我确实,子组件利用传递下来的 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';从反应路由器"导入链接;从反应"导入反应;从'./Home.jsx'导入主页;从'./Nav.jsx'导入导航;从'./Progress.jsx'导入进度;从'./Test.jsx'导入测试;导出默认类 App 扩展 React.Component {构造函数(){极好的();this._fetchPuzzle = this._fetchPuzzle.bind(this);}使成为() {返回 (<路由器><div><导航/><开关><Route path="/"精确测试="hi" component={Home}/><Route path="/progress" test="hi" component={Progress}/><Route path="/test" test="hi" component={Test}/><路由渲染={()=><p>找不到页面!</p>}/></开关>

</路由器>);}}

孩子:

从'react'导入React;const CodeMirror = require('react-codemirror');从'react-router-dom'导入{链接};require('codemirror/mode/javascript/javascript')require('codemirror/mode/xml/xml');require('codemirror/mode/markdown/markdown');导出默认类 Home 扩展 React.Component {构造函数(道具){超级(道具);控制台日志(道具)}使成为() {常量选项 = {行号:真,主题:'abcdef'//模式:this.state.mode};控制台日志(this.props)返回 (<div><h1>首页兄弟</h1><CodeMirror value='code lol' onChange={()=>'do something'} options={options}/>

);}}

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

解决方案

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

<块引用>

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

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

 (<Home test="hi" {...props}/>)}/>

然后你可以像访问它

this.props.test

在您的 Home 组件中

<块引用>

P.S. 还要确保您传递了 {...props} 以便location、history、match etc 等默认路由器道具也被传递到 Home 组件否则,唯一传递给它的 prop 是 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.

这篇关于将自定义道具传递给 react-router v4 中的路由器组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆