首页 > 解决方案 > 如何在另一个文件中调用reactjs路由

问题描述

我想问一个一般性的问题。我有一个menuContent.js类似的东西。

class MenuContent extends Component {  


     constructor(props) {
     super(props)
      this.items = [];


    //   for (let i=1; i<=10; i++) {
    //  //   this.items.push(i)
    //   }
     }


  render() {

    return (

            <div className="menu">

               <a
                href="/animation/animation"
                onClick={this.props.closeCallback}
            >

                <img src={animation} alt="good as"/>
                animation
            </a>
            <br />
            <br />

     )
  }
}

还有一个名为 routing.js 的文件,类似于

class routing extends Component {  


     constructor(props) {
     super(props)
      this.items = [];


    //   for (let i=1; i<=10; i++) {
    //  //   this.items.push(i)
    //   }
     }


  render() {

    return (
        <HashRouter>
            <div className="menu">

                <ul className="header">
                                <li><NavLink to="/animation/animation">Animation</NavLink></li>
                    <li><NavLink to="/bars/bars">Bars</NavLink></li>
                </ul>
                <div className="content">
                    <Route exact path="/" component={Home}/>
                    <Route path="/animation/animation" component={Animation}/>
                    <Route path="/bars/bars" component={Bars}/>
                </div>

但我不知道如何将 routing.js 调用到 menucontent 文件中,除了 <routing /> 进入 menucontent 类

标签: reactjsroutingreact-router

解决方案


我不确定是否完全理解您的问题,但这里是如何在 React 中重用组件。

只需根据需要对组件进行编码并将其导出

import React from 'react';

class Routing extends React.Component {
    // code of component
}

export default Routing;

现在,您的组件路由可用于任何其他脚本。

要重用它,只需导入它并像在同一个文件中一样使用它。

import React from 'react';
import Routing from './Routing.js';

function() {
    return(
        <div>
            <Routing />
        </div>
    );
}

推荐阅读