我正在学习react,我正在学习的课程使用了以前的react版本。导师在ReactDom.render()
中调用routing
。我不知道如何让它在root.render()
内工作。我最终得到一个空白页,而不是应用组件。
index.js
import React from "react";
import ReactDOM from "react-dom/client";
import { Route, Link, Switch, BrowserRouter as Router } from "react-router-dom";
import "./index.css";
import App from "./App";
const routing = (
<Router>
<Route path="/" component={App} />
</Router>
);
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<h1>{routing}</h1>
</React.StrictMode>
);
App.js
import React from "react";
const App = () => {
return (
<div>
<h1>App component</h1>
</div>
);
};
export default App;
适用于React Router v6:
您需要用<Router />
组件包装<App />
删除const routing: ...
,然后这样做:
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter as Router } from "react-router-dom";
import "./index.css";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>
);
现在,在你的应用组件中,用<Routes />
中的特定路由包裹你想要渲染的组件:
import React from "react";
import { Routes, Route } from "react-router-dom";
const App = () => {
return (
<Routes>
<Route path="/" element={<ANY_COMPONENT_YOU_WANT/>} />
</Routes>
);
};
export default App;