react如何设置
安装React
确保Node.js已安装,可以通过官方下载页面获取最新版本。安装完成后,使用npm或yarn初始化项目。
使用Create React App快速搭建项目:
npx create-react-app my-app
cd my-app
npm start
项目结构
典型的React项目结构如下:
my-app/
├── node_modules/
├── public/
│ ├── index.html
│ └── ...
├── src/
│ ├── App.js
│ ├── index.js
│ └── ...
├── package.json
└── ...
组件创建
创建函数组件:
import React from 'react';
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
创建类组件:
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
状态管理
使用useState钩子管理状态:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
路由配置
安装React Router:
npm install react-router-dom
基本路由设置:
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Router>
);
}
样式处理
内联样式:
const divStyle = {
color: 'blue',
fontSize: '20px'
};
function HelloWorld() {
return <div style={divStyle}>Hello World!</div>;
}
CSS模块:
import styles from './App.module.css';
function App() {
return <div className={styles.app}>Content</div>;
}
构建与部署
生成生产版本:
npm run build
部署到静态服务器,可以使用serve:
npm install -g serve
serve -s build






