有没有办法使用React State更改视图?

时间:2017-08-15 14:11:45

标签: reactjs routing react-on-rails

我一直在努力解决这个问题很长一段时间,似乎我找不到解决方案。

在某些情况下,我正在使用的项目不能在Rails上使用React-Router,但我听说有一种方法可以使用State Method在组件之间切换。这是真的吗?

在这个Ruby on Rails应用程序中,我们使用一个父组件,并在其中使用了很多const组件。问题是,我有三个用户需要点击的按钮,当它发生时,内容块必须改变。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

当然,它不是最佳的,但我肯定会调查为什么你不能使用React路由器。尝试打开另一个问题并解决该问题。

import HomeComponent from 'home-component';
import AboutComponent from 'about-component';

const ROUTES = {
  home: HomeComponent,
  about: AboutComponent
};

class MainComponent extends Component {
  state = { component: HomeComponent }

  changeRoute = (routeName) => {
    this.setState({ component: ROUTES[routeName] || HomeComponent });
  }

  render() {
     const { component } = this.state;

     return (
       <div>
         <button onClick={() => changeRoute('home')}>Home</button>
         <button onClick={() => changeRoute('about')}>About</button>
         { component }
       </div>
     );
  }
}

这不是一个很好的方法,显然,复杂性会迅速增加,但它可能适用于小型应用。

相关问题