简体   繁体   English

反应路由器并将道具传递给其他组件

[英]React Router and passing props to other component

I have a button in one component and on click I want to go to other component and pass to this component the state.我在一个组件中有一个按钮,单击时我想将 go 传递给其他组件并将 state 传递给该组件。

It's something like this:是这样的:

import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import AddNewQuestionPage from 'AddNewQuestionPage';

class AddQuestions extends Component {
  state = {
    questions: []
  };

  routeChange = () => {
    let path = `/admin/add-new-question`;
    this.props.history.push(path);
  }

  render() {
    return (
      <>
       <button onClick={this.routeChange}>
          Add new question
       </button>
       <BrowserRouter>
        <Route exact={true} path='/admin/add-new-question' component={AddNewQuestionPage}/>
       </BrowserRouter>
      </>
    )
  }
}

And it doesn't work.它不起作用。 On click I go to add-new-question url but the component AddNewQuestionPage doesn't render.单击我 go 以添加新问题 url 但组件 AddNewQuestionPage 不呈现。 It works if I put Route not in AddQuestions component, but in App component.如果我将 Route 不是放在 AddQuestions 组件中,而是放在 App 组件中,它会起作用。 It's the main component of the whole app and using Switch, there are set also other routes.它是整个应用程序的主要组件,使用 Switch,还设置了其他路由。

However I don't know how I can pass the state questions to AddNewQuestionPage component if it's rendered from App component?但是,如果它是从 App 组件呈现的,我不知道如何将 state 问题传递给 AddNewQuestionPage 组件? I can't just do:我不能这样做:

<Route path='/admin/add-new-question' render={(props) => <AddNewQuestionPage {...props} questions={questions} />

because it doesn't know what is "questions".因为它不知道什么是“问题”。 Lifting the state up to the main component doesn't seem a good solution for me.将 state 提升到主要组件对我来说似乎不是一个好的解决方案。 I was searching and I can't find how to do it...我正在寻找,我找不到如何做到这一点......

You should use the this keyword on the question you're passing to the component.您应该在传递给组件的问题上使用this关键字。

So something like this所以像这样


<Route path='/admin/add-new-question' render={(props) => <AddNewQuestionPage {...props} questions={this.state.questions} />

The best way to use react-router dom is:使用 react-router dom 的最佳方式是:

  1. Always make as a parent component for all.始终将 make 作为所有的父组件。
  2. The best way to change the path by clicking on a sort of component (button...) is You label通过单击某种组件(按钮...)来更改路径的最佳方法是 You label

Please check this guide out: https://reacttraining.com/react-router/web/guides/quick-start请查看本指南: https://reacttraining.com/react-router/web/guides/quick-start

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

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