繁体   English   中英

如何在React路由器中传递道具

[英]How to pass props in react router

我有一个应用程序,一个Navbar和一个Content类,我正在尝试将一个道具从navbar传递到当我重定向到内容页面时将呈现的内容。

App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Navbar from './components/Home/Navbar';
import Content from './components/Home/Content';

export default class App extends Component {

  render() {
      return (
        <Router>
            <div>
              <Navbar />
              <Route path="/content" component={Content} render={(props) => <Navbar {...props} test={this.state.test} />} />
            </div>
        </Router>
    );
  }
}

Navbar.js

import React from 'react';

class Navbar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            test: 'test',
        }
    }

    render() {
        return (

            <div>
                This is my navbar
            </div>

        );
    }
}

export default Navbar;

Content.js

import React from 'react';

class Content extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            x: 'x',
            test: this.props.test
        }
    }

    render() {
        return (

            <div>
                <p>{this.state.x}</p>
                <p>{this.state.test}</p>
            </div>

        );
    }
}

export default Content;

我遇到的问题是,当我重定向到内容页面时,导航栏类的状态没有传递给它。 我该如何解决?

问题主要在于您在Route同时使用了componentrender道具,因此您只能使用其中一个。 如果你不想改变或沿着从任何地方通过Route定义,你应该使用component属性。

如果您确实希望在那时传递一些信息,请使用已完成的render道具(但是,我相信您确实想渲染Content组件,而不是OP中的NavBar )。

<Route path="/content" render={(props) => <Content {...props} test={this.state.test} />} />

然后,您实际上不需要显示的任何本地状态,而是内容可以是功能组件,例如

const Content = ({ x, test }) => (
  <>
    <p>{ x }</p>
    <p>{ test }</p>
  </>);

xtest将从props中解构出来,使您可以轻松访问它(也可以使用(props) ,然后使用props.testprops.x具体取决于您的编写方式)

你可以通过重定向传递这样的状态:

<Redirect to={{
            pathname: '/content',
            state: { test: '123' }
        }}
/>

和访问它:

this.props.location.state.test

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM