我怎样才能通过在 react、chrome 扩展中按下按钮来重定向到另一个组件?

我在 Rect 中创建了 chrome 扩展。我怎样才能通过在 react、chrome 扩展中按下按钮来重定向到另一个组件?


我怎样才能从App组件(按下按钮后)重定向到ItemDetails组件?不使用条件(三元运算符)。


我找到了这样一篇文章:Routing in Chrome Extension write in React


import { createMemoryHistory } from 'history'

const history = createMemoryHistory()


render() {

  let page = null

  switch (this.state.page) {

  case 'home':

    page = <Home />

    break

  case 'user':

    page = <User />

    break

  }

  return page

}

我不明白这一点this.state.page。如果我想转到另一个组件,我怎样才能得到这个this.state.page. 如何将组件名称保存在它想要进入的状态?

import React, { Component } from 'react';

import { render } from 'react-dom';

import axios from 'axios';



class ItemDetails extends Component {

  constructor(){

    super();

  }


  render() {


    return (  

      <div>

        <p>

            Description:vvvvvvvvvvv

        </p>

      </div>

    )

  }

}


class App extends React.Component {

  constructor() {

    super();


    this.state = {

      items: [

        {

          name: 'A',

          description: 'Hello'

        }

      ],

      form: {}

    };

  }


  render() {


    return (

      <div>

         <form action="" method="post" onSubmit={this.onSubmit}>


            <button type="submit" value="Submit" >Log in</button>

          </form>  

      </div>

    );

  }

}



render(<App />, document.getElementById('root'));


慕姐8265434
浏览 169回答 3
3回答

猛跑小猪

您需要使用Routes重定向到其他组件。你可以让路线像,import { BrowserRouter, Route, Switch } from "react-router-dom";<BrowserRouter>&nbsp; &nbsp;<Switch>&nbsp; &nbsp; &nbsp; <Route exact path='/' component={Dashboard} />&nbsp; &nbsp; &nbsp; <Route exact path='/itemDetails' component={ItemDetails} />&nbsp; &nbsp;</Switch></BrowserRouter>在具有重定向按钮的组件中,您需要使用withRouter.import { withRouter } from 'react-router-dom';class Dashboard extends React.Component {&nbsp; onSubmit = () => {&nbsp; &nbsp; this.props.history.push('/itemDetails');&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<form onSubmit={this.onSubmit}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button type="submit" >Log in</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </form>&nbsp;&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}export default withRouter(Dashboard)演示注意:不要action="" method="post"在表格上使用。

至尊宝的传说

您可以使用 react-router-dom。首先,当您安装路由器时,您需要导入一些东西。import { BrowserRouter, Route } from 'react-router-dom';比您需要为页面设置不同的路由,例如:<BrowserRouter>&nbsp; <App>&nbsp; &nbsp; <Route path="/" exact component={App} />&nbsp; &nbsp; <Route path="/details" component={ItemDetails} />&nbsp; </App></BrowserRouter>在您的应用程序组件 onSubmit 函数中,您可以使用 history 对象将用户推送到特定页面:onSubmit = () => {&nbsp; this.props.history.push('/details');};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript