Reactのルーティング設定方法は何ですか?

Reactのルート設定には多くの方法がありますが、一般的なものは以下のいくつかです:

  1. react-router-dom パッケージの BrowserRouter または HashRouter コンポーネントを使用して、アプリケーション全体をラップし、その内部でルーティング規則を設定します。例:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </Switch>
    </Router>
  );
}
  1. react-router-dom パッケージの Route コンポーネントを使用して、ネストされたルーティング規則を設定します。例えば:
import { Route } from 'react-router-dom';

function App() {
  return (
    <>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </>
  );
}
  1. react-router-dom パッケージに含まれる withRouter 高階コンポーネントを使用して、ルート情報を取得する必要があるコンポーネントをラップします。例:
import { withRouter } from 'react-router-dom';

function MyComponent(props) {
  // 可以通过 props 获取路由信息,如 props.history, props.location, props.match
  return <div>Hello React Router!</div>;
}

export default withRouter(MyComponent);

react-router-dom パッケージのコンポーネントやHOCを使用して、ルーティング規則を設定し、ルーティング情報を取得する方法について説明しました。具体的な方法の選択は、プロジェクトの要件や個人の好みに基づいて決めてください。

bannerAds