以下是搭建一个React+TypeScript项目的基本步骤,包括集成Router、Redux以及样式处理:
- 初始化项目:
npx create-react-app my-app --template typescript
- 安装
react-router-dom
:
npm install react-router-dom
- 安装
react-redux
和redux
:
npm install react-redux redux
- 安装
redux-thunk
中间件(如果需要异步actions):
npm install redux-thunk
- 安装
less
和less-loader
以支持LESS文件:
npm install less less-loader
- 安装
postcss-px2rem
以转换单位:
npm install postcss-px2rem
- 在
src
目录下创建redux
文件夹,并初始化store.ts
:
// src/redux/store.ts
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
- 在
src
目录下创建redux/reducers.ts
:
// src/redux/reducers.ts
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
// 定义reducers
});
export default rootReducer;
- 在
src
目录下创建redux/actions.ts
:
// src/redux/actions.ts
// 定义actions
- 修改
index.tsx
以使用Redux和React Router:
// src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import store from './redux/store';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
- 在
src/App.tsx
中添加路由:
// src/App.tsx
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import HomePage from './HomePage';
function App() {
return (
<div>
<Switch>
<Route path="/home" component={HomePage} />
{/* 其他路由 */}
</Switch>
</div>
);
}
export default App;
- 在
src
目录下创建HomePage.tsx
组件:
// src/HomePage.tsx
import React from 'react';
const HomePage: React.FC = () =>