首页 文章

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

提问于
浏览
11

我正在使用React Router创建一个多页面应用程序 . 我的主要组件是 <App/> ,它将所有路由呈现给子组件 . 我正在尝试通过路径传递道具,并且基于我所做的一些research,子组件最常用的方法是传递到传递的道具是通过它们继承的 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很新,所以如果我错过了一些明显的东西我会道歉 . 谢谢!

1 回答

  • 22

    您可以通过将 render prop添加到 Route 并因此内联组件定义来将props传递给组件 . 根据 the DOCS:

    这样可以方便地进行内联渲染和换行,而无需上面说明的不需要的重新安装 . 使用组件prop为您创建一个新的React元素,您可以传入一个函数,以便在位置匹配时调用 . 渲染道具接收与组件渲染道具相同的所有路径道具

    所以你可以把道具传递给像这样的组件

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

    然后你可以像访问它一样访问它

    this.props.test
    

    Home 组件中

    P.S.还要确保你传递,以便默认的路由器道具如位置,历史,匹配等也会传递给Home组件,否则传递给它的唯一道具就是测试 .

相关问题