使用react-router在<Link to =''>中包装<button>

时间:2019-06-20 18:00:11

标签: javascript reactjs react-router

我有3个链接到不同页面的按钮。主页是唯一应该显示按钮(App.js)的页面。我创建了另外两个页面,table1.js,table2.js,table3.js,它们都显示不同的内容。我的问题是,当我单击任意一个按钮时,它会将我定向到正确的页面(例如Enumerable#sort_by),但这些按钮仍在显示。有什么方法可以执行“将用户定向到新页面后删除按钮”之类的方法吗?

class App extends Component {

render() {
    return (
      <div className="App">   
        <form className='button-container'>
        <Router>
          <div> 
          <Route exact path='/table1' component={table1}/>
          <Link to="/table1" className='button'>
            <button className='button' type="button">
                  Table 1        
            </button>
          </Link>
          </div>
          <div>
          <Route exact path='/table2' component={table2}/>
          <Link to="/table2" className='button'>
            <button className='button' type="button">
                  Table 2        
            </button>
          </Link>
          </div>
          <div>
          <Route exact path='/table3' component={table3}/>
          <Link to="/table3" className='button'>
            <button className='button' type="button">
                  Table 3        
            </button>
          </Link>
          </div>
        </Router>
        </form>
      </div>
    );
  }
}
export default App;

1 个答案:

答案 0 :(得分:2)

您可能应该将按钮布线到不同的组件中,并且还仅根据路线或条件来呈现按钮:

class Navigation extends Component {
  render() {
    return (
      <form className="button-container">
        <Link to="/table1" className="button">
          <button className="button" type="button">
            Table 1
          </button>
        </Link>
        <Link to="/table2" className="button">
          <button className="button" type="button">
            Table 2
          </button>
        </Link>
        <Link to="/table3" className="button">
          <button className="button" type="button">
            Table 3
          </button>
        </Link>
      </form>
    );
  }
}

class App extends Component {
  render() {
    return (
      <div className="App">
        <Router>
          <Switch> {/* only matches one route */}
            <Route exact path="/table1" component={table1} />
            <Route exact path="/table2" component={table2} />
            <Route exact path="/table3" component={table3} />
            <Route component={Navigation} /> {/* If no routes matched show Navigation */}
          </Switch>
        </Router>
      </div>
    );
  }
}
export default App;