簡體   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